【发布时间】:2018-06-05 09:08:50
【问题描述】:
我有以下代码,我需要从变量中获取列名,然后使用该操作中的指定列有选择地对行执行操作。这是我的简单示例,创建列res 以匹配列target:
library(tidyverse)
tst <- tibble(grp = c("a","a","b","b","c","c"), a = rep(2,6), b = rep(4,6),
c = rep(8,6), target = c(2,2,4,4,8,8), res = rep(0,6))
# create list of columns to iterate over
lst <- unique(tst$grp)
# loop over each column, creating a dummy column with
# the copied value in the matching rows, zeroes elsewhere
for(g in lst) {
tst <- tst %>%
mutate(!!paste("res", g, sep="_") := ifelse(grp == g, !!rlang::sym(g),0)) %>%
select(!!paste("res", g, sep="_")) %>%
cbind(tst)
}
# combine the dummy columns by rowSum
res <- tst %>% select(starts_with("res_")) %>% mutate(res = rowSums(.)) %>%
select(res)
# tidy up the output, result matches the target
tst <- tst %>% select(grp, a, b, c, target) %>% cbind(res)
tst
grp a b c target res
1 a 2 4 8 2 2
2 a 2 4 8 2 2
3 b 2 4 8 4 4
4 b 2 4 8 4 4
5 c 2 4 8 8 8
6 c 2 4 8 8 8
我采用了一种迭代方法,循环遍历 grp 列中的唯一变量,创建临时列然后 rowSum()ing 这些以获得最终结果。笨重,但最终到达那里。
我确信有一种更优雅的方法可以使用来自purrr 的map 家族之一。有人可以告诉我如何在没有循环的情况下使用purrr 做到这一点吗?我真的很努力让动态列名使用这种方法工作。提前致谢。
【问题讨论】: