跨多个列运行函数

时间:2019-03-18 03:58:46

标签: r

我正在尝试清除已提供给我的六十列数据摘录。数据的一部分大约是三十列,这些列已作为“是”或“否”值提供,我希望将其转换为逻辑类型。因此,它并不是数据框中的每一列,但其中有很多。我目前正在执行以下操作:

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

也就是说,手动更改列表中的每一列。但这感觉很容易由于缺少复制粘贴或类似内容而出错。是否有一个函数可以通过传递字段名称列表来一步完成此操作?我倾向于默认使用tidyverse函数,尽管如果需要,基数R也可以使用。

2 个答案:

答案 0 :(得分:1)

这应该是重复的,但现在找不到相关的帖子。

我们可以使用mutate_at并将功能应用于选定的列

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

或者,如果我们将列名存储在名为cols的向量中,则可以这样做

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

答案 1 :(得分:0)

也许您可以使用lapply()

lapply(mtcars, as.character)

如果您希望将数据作为数据框:

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"