user3620588
user3620588

Reputation: 41

From factor to Numeric in R

I am having big trouble trying to convert a set of 53 factor variables to numeric. Here are a couple of the functions I tried but none of them are working :

sapply(dataset, function(x) transform(as.character(x)))

and then

sapply(dataset, function(x) transform(as.numeric(x)))

I also tried it with lapply, but same thing...

as.numeric(levels(factor)) 

doesnt work either and finally I tried to do it one by one:

transform(dataset, s1 = as.numeric(s1), s2= as.numeric(s2)...etc)

Could somebody please help me ? I also have a couple of missing values NA and M within the variables so I dont know how I can adjust for that. Thanks !

Upvotes: 0

Views: 170

Answers (1)

Jaap
Jaap

Reputation: 83215

Although you didn't provide a reproducible example, this might work:

df[,c(2:54)] <- as.numeric(as.character(unlist(df[,c(2:54)])))

where c(2:54) stands for the columns you want to change to numeric

Upvotes: 1

Related Questions