简体   繁体   中英

r: convert multiple factors to numeric simultaneously

I know how to convert one factor of a dataframe to numeric:

rds$fcv12afa3num <- as.numeric(levels(rds$fcv12afa3))[rds$fcv12afa3]

My two questions:

  1. But how can I convert all dataframe-columns simultaneously, if the df consists only of factors?
  2. How can I convert several factors simultaneously, based on a pattern of the column name?

I have many NA's, if that matters.

Thanks for your answer, Christian

Without example data, I can't give a completely exact answer, but this should get you started.

factorVars <- names(YourData)[vapply(YourData, is.factor, logical(1))]

YourData[, factorVars] <- lapply(YourData[, factorVars, drop = FALSE],
            as.numeric)

Some notes:

  1. Use drop = FALSE to handle the case of there only being one factor in your data frame.
  2. If all of the factors are data frames, you may get a list object in return. You'd have to run that list through as.data.frame to get your data frame back.

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