# Create a vector with NA
a <- as.character(c(1:5, NA, seq(from=6, to=7, by=0.2)))
# see what we created
print(a)
# check if the vector is all numbers (not ignoring NAs)
check.numeric(a)
# check if the vector is all numbers (ignoring NAs)
check.numeric(a, na.rm=TRUE)
# if all the items in vector a are safe for numeric conversion
if(all(check.numeric(a))){
# convert the vector to numeric
a <- as.numeric(a)
}
# create a complicated vector
b <- c("1", "2.2", "3.", ".4", ".5.", "..6", "seven", "00008",
"90000", "-10", "+11", "12-", "--13", "++14", NA, "",
" 7 ", " ", "8e2", "8.6e-10", "-8.6e+10", "e3")
# show in proper format
print(data.frame(value=b, check.numeric=check.numeric(b), converted=as.numeric(b)))
# value check.numeric converted
# 1 1 TRUE 1.0e+00
# 2 2.2 TRUE 2.2e+00
# 3 3. TRUE 3.0e+00
# 4 .4 TRUE 4.0e-01
# 5 .5. FALSE NA
# 6 ..6 FALSE NA
# 7 seven FALSE NA
# 8 00008 TRUE 8.0e+00
# 9 90000 TRUE 9.0e+04
# 10 -10 TRUE -1.0e+01
# 11 +11 TRUE 1.1e+01
# 12 12- FALSE NA
# 13 --13 FALSE NA
# 14 ++14 FALSE NA
# 15 TRUE NA
# 16 TRUE NA
# 17 7 TRUE 7.0e+00
# 18 TRUE NA
# 19 8e2 TRUE 8.0e+02
# 20 8.6e-10 TRUE 8.6e-10
# 21 -8.6e+10 TRUE -8.6e+10
# 22 e3 FALSE NA
# remember that "" and " " can be converted to numeric safely, but their value would be NA.
Run the code above in your browser using DataLab