OneBite.Dev - Coding blog in a bite size

check if a string contains only numbers in R

Code snippet on how to check if a string contains only numbers in R

  as.numeric(as.character(x)) == x

This code compares an inputted string, x, to a numeric version of itself using the as.character and as.numeric functions in R. If these two results are equal then the string contains only numbers and the code will output TRUE. This code works because the as.numeric function will return a NA (not available) value if its argument is not a number, but the as.character function will not detect that, so it will create a numeric conversion of the string. The comparison will then return FALSE if the inputted string was not exclusively numeric.

r