[英]dplyr group_by and replace all columns with a function of the group
[英]dplyr: Send all Columns to a function within a mutate following a group_by
在dplyr管道中調用任意函數時,將當前組中的所有列作為小標題或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]))
這是我的答案,不知道要計算平均值的列。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.