首页 文章

dplyr:将所有列发送到group_by之后的mutate中的函数

提问于
浏览
2

在调用dplyr管道中的任意函数时,将当前组中的所有列作为tibble或data.frame发送到函数的首选方法是什么?

在下面的示例中, mean_B 是一个简单的示例,我知道在进行函数调用之前需要什么 . mean_B_fun 给出了错误的答案(与我想要的相比 - 我想要组内的意思), mean_B_fun_ugly 给出了我想要的东西,但它似乎是一种低效(和丑陋)的方式来获得我想要的效果 .

我想在任意列上操作的原因是,在实践中,我在用户的下面的示例中使用 my_fun ,并且我不知道用户需要先验地操作的列 .

library(dplyr)

my_fun <- function(x) mean(x$B)

my_data <-
  expand.grid(A=1:3, B=1:2) %>%
  mutate(B=A*B) %>%
  group_by(A) %>%
  mutate(mean_B=mean(B),
         mean_B_fun=my_fun(.),
         mean_B_fun_ugly=my_fun(as.data.frame(.)[.$A == unique(A),,drop=FALSE]))

1 回答

  • 0

    这是我的答案,不知道你想要计算平均值的列 .

    expand.grid(A=1:3, B=1:2) %>%
    mutate(B=A*B) %>% nest(-A)  %>%
    mutate(means = map(.$data, function(x) colMeans(x)))
    
      A data means
    1 1 1, 2   1.5
    2 2 2, 4     3
    3 3 3, 6   4.5
    

相关问题