from character to numeric in r

To convert a character variable to a numeric variable in R, you can use the as.numeric() function. Here's an example:

main.r
# create a character variable
my_char <- "123"

# convert the character variable to numeric
my_num <- as.numeric(my_char)

# print the result
print(my_num)
156 chars
9 lines

This will output:

main.r
[1] 123
8 chars
2 lines

Note that if the character variable cannot be converted to a numeric variable (e.g., if it contains letters or other non-numeric characters), as.numeric() will return NA. You can check for this using the is.na() function. For example:

main.r
# create a character variable with non-numeric characters
my_char <- "abc123"

# convert the character variable to numeric
my_num <- as.numeric(my_char)

# check if the result is NA
print(is.na(my_num))
203 chars
9 lines

This will output:

main.r
[1] TRUE
9 chars
2 lines

gistlibby LogSnag