Search code examples
rintegercoercion

R: How to convert factors into numeric for a DATA FRAME?


I want to convert factors into numeric. I know this a FAQ, I tried already as.numeric(levels(f))[f] and as.numeric(as.character(f)). But this doesn't help as I want to convert all columns (more than 1000 and all of type factor) of the df into numeric. How can I do this?


Solution

  • We can try

     yourdat[] <- lapply(yourdat, function(x) if(is.factor(x)) as.numeric(levels(x))[x]
                                  else x)