Home > Mobile >  R How to effectively change datatype of an entire column from char to numeric/double in R
R How to effectively change datatype of an entire column from char to numeric/double in R

Time:09-01

I've tried couple of ways to change some selected columns of my data set from chr to num, but 2 columns have failed to changed while the remaining 14columns changed effectively. Viewing the dataset, I noticed that a row across both column has an exponential value in the form of (2.4999999999863576E-2) and (1.6000000000076398E-2) on row 5 of the picture.

Here are the code samples I've tried

animals[3:16] <- sapply(animals[3:16], as.numeric)

I found that column 12 and 13 refused to change bcos they include an exponent value

and I've also tried this belowScreenshot of viewing the animal dataset:

animals <- animals %>%
  mutate(animals[3:16], as.numeric) %>%
  str()

CodePudding user response:

We may use lapply instead of sapply as sapply returns a matrix and this can have only a single class i.e. if there is any column that is a character, it can result in character

animals[3:16] <- lapply(animals[3:16], as.numeric)

Or with dplyr, use across to loop over the columns

library(dplyr)
animals <- animals %>%
     mutate(across(3:16, as.numeric))

CodePudding user response:

Try to combine with format function.

For instance,

as.numeric("12389054328902")
"1.238905e 13"
format(as.numeric("12389054328902"), scientific = F)
"12389054328902"
  •  Tags:  
  • r
  • Related