简体   繁体   中英

I want to isolate multiple columns in a dataframe from a vector source and convert their data type from character to numeric using R

I have a dataframe

col1|col2|col3|cola|colb|colc|cold
 "1"   "1"  "1"    x    x    x    x

Then I have a vector

 colnum<-c("col1","col2","col3")

I use this script to convert the specific columns in the dataframe from the vector as a source from charcacter into numeric

df[colnum] <- sapply(df[column],as.numeric)

When I first tried it it worked, but after using it again it gave me this message

Error in lapply(X = X, FUN = FUN, ...) : 

'list' object cannot be coerced to type 'double'

It is better to use lapply instead of sapply as this can convert to matrix while lapply always returns a list and a data.frame is a list as well (with list elements ie columns of equal length )

df[colnum] <- lapply(df[colnum],as.numeric)

In the OP's code, there is a typo as well. Instead of colnum , it is written as column

Update

Based on the OP's comments, it seems that some columns are list as well. In that case, we loop over those columns with lapply , unlist the list and convert to numeric

df[colnum] <- lapply(df[colnum], function(x) as.numeric(unlist(x)))

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