【发布时间】:2020-08-14 12:33:22
【问题描述】:
我正在尝试使用函数group_modify(我已经了解了here)。
目标是获取data.frame,将其与group_by 拆分,然后应用自制函数进行一些重组(即排序,选择“最佳行”,如果超过一个,则取平均值) .我需要输出 data.frame 具有 all 原始列的列。
这是一个让一切变得更清晰的 RE:
数据:
library(dplyr)
(dd <- data.frame(id = c("a", "a", "b", "b", "c", "c", "c"), cat = c("s2", "s1", "s1", "s1", "s3", "s2", "s2"), val = 1:7))
id cat val
1 a s2 1
2 a s1 2
3 b s1 3
4 b s1 4
5 c s3 5
6 c s2 6
7 c s2 7
我的功能(显示我的问题的基本功能,但不完全是我实际使用的功能):
simple_fun <- function(slice, key){
big_out_to_show_error <<- slice
temp1 <- arrange(slice, cat)
temp2 <- temp1 %>%
filter(cat==temp1$cat[1])
if(nrow(temp2)>1) {
temp2 <- temp2 %>%
group_by(id, cat) %>%
summarise(val = mean(val))
}
return(data.frame(temp2))
}
我想要的输出(每个 ID 一行具有“最佳”cat,如果超过一行,则为 val 的平均值,并且具有原始 data.frame 中的所有变量):
id cat val
a a s1 2.0
b b s1 3.5
c c s2 6.5
我对@987654332@ 函数的尝试抛出了一个错误:
dd %>%
group_by(id) %>%
group_modify(simple_fun)
Show Traceback
Rerun with Debug
Error: Column `id` is unknown
这是因为使用的slice 不包括分组变量。从这个简单的代码可以看出这一点,它在 main 函数中使用了 big_out_to_show_error <<- slice 行并限制为 id=="a":
filter(dd, id=="a") %>%
group_by(id) %>%
group_modify(simple_fun)
# A tibble: 1 x 3
# Groups: id [1]
id cat val
<fct> <fct> <int>
1 a s1 2
big_out_to_show_error
# A tibble: 2 x 2
cat val
<fct> <int>
1 s2 1
2 s1 2
如何管理 group_by 函数以仍然将分组变量放入切片中,以便我的函数与 group_modify 一起使用?
作为旁注,我真的很想了解和修复 dplyr group_by 的行为。我已经知道基本的 R 方法:
split(dd, dd$id) %>%
lapply(simple_fun) %>%
do.call("rbind", .)
id cat val
a a s1 2.0
b b s1 3.5
c c s2 6.5
谢谢
【问题讨论】: