[英]mutate_at with two sets of variables
I just asked a question about generating multiple columns at once with dplyr
, and I'm a bonehead and oversimplified the problem and have another question. 我刚刚问了一个关于用
dplyr
一次生成多个列的问题 ,我是一个dplyr
,并且过度简化了问题,还有另外一个问题。 I'd like to find a dplyr
method for dynamically generating columns based on other columns. 我想找到一个
dplyr
方法,用于根据其他列动态生成列。
cols <- c("x", "y")
foo <- c("a", "b")
bar <- c("c", "d")
df <- data.frame(a = 1, b = 2, c = 10, d = 20)
df[cols] <- df[foo] * df[bar]
In my first iteration of the question, I included only one set of previously defined columns, so the following worked: 在我问题的第一次迭代中,我只包含了一组先前定义的列,因此以下工作:
df %>%
mutate_at(vars(foo), list(new = ~ . * 5)) %>%
rename_at(vars(matches('new')), ~ c('x', 'y'))
However, as the first few lines of code suggest, I would like to instead multiply two existing columns together, and am unable to figure out how to do this. 但是,正如前几行代码所示,我想将两个现有列相乘,而我无法弄清楚如何执行此操作。 I have tried:
我试过了:
df %>%
mutate_at(c(vars(foo), vars(bar)),
function(x,y) {x * y})
which returns the error: 返回错误:
Error in (function (x, y) : argument "y" is missing, with no default
Is it possible to reference multiple sets of columns to be used on each other with mutate_at
? 是否可以使用
mutate_at
引用彼此使用的多组列?
Well as you want to work with two columns, I think purrr::map2
is the function to work with: 好吧,因为你想使用两列,我认为
purrr::map2
是可以使用的函数:
library(purrr)
library(dplyr)
map2(foo, bar, ~ df[[.x]] * df[[.y]]) %>%
set_names(cols) %>%
bind_cols(df, .)
#> a b c d x y
#> 1 1 2 10 20 10 40
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.