简体   繁体   中英

Run a function across multiple columns

I'm trying to clean a sixty column data extract that has been given to me. Part of the data is about thirty columns which have been supplied as "Yes" or "No" values that I would like to convert to logical type. It therefore isn't every column in the data frame, but it is a lot of them. I'm currently doing the equivalent of this:

mtcars %>%
  mutate(mpg = as.character(mpg)) %>%
  mutate(cyl = as.character(cyl)) %>%
  mutate(disp = as.character(disp)) %>%
  mutate(hp = as.character(hp))

That is, manually mutating each column in the list. But that feels like it will be prone to error from missing a copy-paste or similar. Is there a function that could do this in one step by being passed a list of field names? I tend to default to tidyverse functions, though base R also works if needed.

This should be a duplicate but cannot find a relevant post right now.

We can use mutate_at and apply function on selected columns

library(dplyr)
mtcars %>% mutate_at(vars(mpg, cyl, disp, hp), as.character)

Or if we have column names stored in vector called cols we could do

cols <- c("mpg", "cyl", "disp", "hp")
mtcars %>% mutate_at(cols, as.character)

Perhaps you can use lapply() ?

lapply(mtcars, as.character)

If you would like your data as a data frame:

df = as.data.frame( lapply(mtcars, as.character), stringsAsFactors = F )

> df$mpg
 [1] "21"   "21"   "22.8" "21.4" "18.7" "18.1" "14.3" "24.4" "22.8"
[10] "19.2" "17.8" "16.4" "17.3" "15.2" "10.4" "10.4" "14.7" "32.4"
[19] "30.4" "33.9" "21.5" "15.5" "15.2" "13.3" "19.2" "27.3" "26"  
[28] "30.4" "15.8" "19.7" "15"   "21.4"

> df$cyl
 [1] "6" "6" "4" "6" "8" "6" "8" "4" "4" "6" "6" "8" "8" "8" "8" "8"
[17] "8" "4" "4" "4" "4" "8" "8" "8" "8" "4" "4" "4" "8" "6" "8" "4"

> df$disp
 [1] "160"   "160"   "108"   "258"   "360"   "225"   "360"   "146.7"
 [9] "140.8" "167.6" "167.6" "275.8" "275.8" "275.8" "472"   "460"  
[17] "440"   "78.7"  "75.7"  "71.1"  "120.1" "318"   "304"   "350"  
[25] "400"   "79"    "120.3" "95.1"  "351"   "145"   "301"   "121"  

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