If statement create NA

Is it possible to create an if statement, where observations in a column (measure) is kept as it is if it contains numbers but converted to NA if it contains letters?


id measure
1 1 10
2 2 AB
3 3 41
4 4 CGHa
5 5 100

Thank you

Your measure column in your data data.frame currently contains a charcter vector. The c() function will convert your numerics to characters, so:

measure <- c(10,"AB",41,"CGHa",100)

is the same as:

measure <- c("10","AB","41","CGHa","100")

This is called coercion and R does it a lot whenever values are of different types.

You can exploit this by using as.numeric() which will return NA when it cannot convert a character to a numeric.

data$measure <- as.numeric(data$measure)

It will give you a Warning that some values could not be converted, but if you are sure that you don't want the character values, then this Warning can be ignored.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.