简体   繁体   中英

How do I convert an entire column to numeric based on whether the column is all numbers (but in character format)?

I have a very large dataset with many columns so instead of converting each column from character to numeric by hand, I would like to do it automatically. Since the values in the column are "0", "1", "2"... "9", ("1" through "9"), I imagine some sort of for loop that runs through each column, checks if the column is all "0", "1", "2"... or, "9", then converts them all to numeric.

What is the best way to do this?

You can convert the values to numeric if all the column values are a number.

df[] <- lapply(df, function(x) if(all(grepl('^\\d+$', x))) as.numeric(x) else x)

Using dplyr -

library(dplyr)

df <- df %>% mutate(across(where(~all(grepl('^\\d+$', .x))), as.numeric)) 

Using base R . We don't need any regex - this can be automatically converted to numeric types with type.convert

df <- type.convert(df, as.is = TRUE)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM