user35131
user35131

Reputation: 1134

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'

Upvotes: 1

Views: 66

Answers (1)

akrun
akrun

Reputation: 886938

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 i.e. 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)))

Upvotes: 1

Related Questions