简体   繁体   中英

How do I convert all factor columns to numeric that have colnames matching from a list of strings?

I have not found this exact issue yet on here. I have many columns and for all the ones that match ANY of a list of strings, I want to convert from factor -> character -> numeric.

Below shows an example where columns containing one of the strings are converted, and the two things I've tried for the case of multiple strings that failed

#Making fake data where every column is a factor. At the end I'd like to convert all factors that contain either "alcium" or "zinc" in the column name.
library(reshape2)
fake <-data.frame(id=c(1,1,1,2,2,2,3,3,3,1,1,1,2,2,2,3,3,3),              
              time=c(rep("Time1",9), rep("Time2",9)), 
            test=c("calcium","magnesium","zinc","calcium","magnesium","zinc","calcium","magnesium","zinc","calcium","magnesium","zinc","calcium","magnesium","zinc","calcium","magnesium","zinc"), 
              score=floor(runif(18, min=1, max=5)))

fake <- dcast(fake, id ~ time + test)
fake <- fake %>% mutate_if(is.numeric,as.factor)

#This works, but only for columns containing one of the strings
fake <- fake %>% mutate_at(vars(contains('alcium')),  function(x) as.numeric(as.character(x))) 

#Now trying to convert all columns containing either "alcium" or "zinc"
fake <- fake %>% mutate_at(vars(contains('alcium'| 'zinc')),  function(x) as.numeric(as.character(x))) 
#gives an error

#2nd attempt:
strings <- c("alcium", "zinc")
fake <- fake %>% mutate_at(vars(contains(strings)),  function(x) as.numeric(as.character(x)))  
#gives an error

Using the select helper matches() instead of contains() allows the passing of the strings collapsed into a regex friendly format.

library(dplyr)
strings <- c("alcium", "zinc")

fake %>%
  as_tibble %>%
  mutate_at(vars(matches(paste0(strings, collapse = "|"))),  as.numeric) 

# A tibble: 3 x 8
  id    Time1_calcium `Time1_ma    gnesium` Time1_magnesium Time1_zinc Time2_calcium Time2_magnesium Time2_zinc
  <fct>         <dbl> <fct>                 <fct>                <dbl>         <dbl> <fct>                <dbl>
1 1                 2 NA                    4                        1             3 4                        1
2 2                 2 NA                    3                        2             1 1                        3
3 3                 1 3                     NA                       1             2 3                        2

I have updated your code a bit.

If you don't have too many you could do them separately. Otherwise, I couldn't get multiple strings to work.

sofaWa <- fake %>% mutate_at(vars(contains('alcium')), list(as.numeric)) %>% 
  mutate_at(vars(contains('zinc')), list(as.numeric)) 

Produces this

# A tibble: 3 x 7
  id    Time1_calcium Time1_magnesium Time1_zinc Time2_calcium Time2_magnesium Time2_zinc
  <fct>         <dbl> <fct>                <dbl>         <dbl> <fct>                <dbl>
1 1                 3 2                        1             1 2                        1
2 2                 2 1                        2             1 1                        2
3 3                 1 4                        2             2 3                        1

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