Reputation: 355
I would like to convert all columns of a df from character to numeric.
df example:
A B C D
"1" "10.2" "0.2" "8"
"5" "2.1" "0.5" "6"
"3" "4.6" "0.3" "7"
Convert character values in all columns (A,B,C,D) to numeric. Thanks!
Upvotes: 0
Views: 1417
Reputation: 1173
I like doing it this way.
data <- apply(df, 1, fun(x) as.numeric(x))
Upvotes: 0
Reputation: 886938
We can use lapply
df[] <- lapply(df, function(x) if(is.character(x)) as.numeric(x)
else x)
If we know that all columns are 'character' and needs conversion
df[] <- lapply(df, as.numeric)
Upvotes: 1
Reputation: 14192
Lots of ways of doing this. I like this approach by purrr
library(purrr)
df %>% map_if(is.character, as.numeric)
str(df)
'data.frame': 3 obs. of 4 variables:
$ A: num 1 5 3
$ B: num 10.2 2.1 4.6
$ C: num 0.2 0.5 0.3
$ D: num 8 6 7
Upvotes: 5
Reputation: 414
Have a look at this: R Convert quoted numbers to numeric
Basically you can use the apply()
function inconjunction with as.numeric()
to convert the numbers as string to numeric.
Upvotes: 0