我想一次将mutate
函数应用于多个列。列以某些字符串开头,这就是应该如何识别它们的方式。我也想知道该解决方案如何将其应用于由索引即标记的列。 data_fake[3:4]
。目的是删除所有非数字字符并将值转换为数字。不能让人悲伤地工作。所需的结果在代码末尾给出。非常感谢。
data_fake <- data.frame(c("1","2","NA","3,","2","1 only"),c(1,2,3,4,5,6),
c("23","3 bundles","4","5","NA","1"), c("3","5 packs","6","78","7","8"))
colnames(data_fake) <- c("AB foo ab", "AB foo bc", "CD foo ab","CD foo bc")
data_fake <- as_tibble(data_fake)
data_fake %>%
select(starts_with("CD foo")) %>%
mutate(as.numeric(gsub("[^0-9]", "")))
data_fake_results <- as_tibble(data.frame(c("1","2","NA","3,","2","1 only"),c(1,2,3,4,5,6),
c(23,3,4,5,NA,1), c(3,5,6,78,7,8)))
答案 0 :(得分:4)
我们可以使用mutate_at
library(tidyverse)
data_fake %>%
mutate_at(vars(3:4), funs(as.numeric(str_remove(., "\\s+[a-z]+"))))
或使用parse_number
data_fake %>%
mutate_at(3:4, parse_number)
如果我们要匹配mutate_at
中的列名
data_fake %>%
mutate_at(vars(starts_with("CD")), parse_number)