你能在dplyr链中使用两次data.frame吗?dplyr说"错误:无法处理"

Joh*_*aul 2 r dplyr

我试图在dplyr链中使用两次data.frame .这是一个给出错误的简单示例

df <- data.frame(Value=1:10,Type=rep(c("A","B"),5))

df %>% 
  group_by(Type) %>% 
  summarize(X=n())  %>% 
  mutate(df %>%filter(Value>2) %>%  
  group_by(Type) %>%  
  summarize(Y=sum(Value)))

Error: cannot handle
Run Code Online (Sandbox Code Playgroud)

因此,我们的想法是首先data.frame创建两个列Value,这两个列只是一些数据,Type它指示值来自哪个组.

然后我尝试使用汇总来获取每个组中的对象数,然后在数据被过滤后再次使用该对象来获取值的总和.但是我得到了Error: cannot handle.有什么想法在这里发生了什么?

期望的输出:

Type X Y
  A  5 24
  B  5 28
Run Code Online (Sandbox Code Playgroud)

Dav*_*urg 6

您可以尝试以下方法

df %>% 
  group_by(Type) %>% 
  summarise(X = n(), Y = sum(Value[Value > 2]))

# Source: local data frame [2 x 3]
# 
#   Type X  Y
# 1    A 5 24
# 2    B 5 28
Run Code Online (Sandbox Code Playgroud)

我们的想法是仅Value根据所需条件进行过滤,而不是整个数据集


和奖金解决方案

library(data.table)
setDT(df)[, .(X = .N, Y = sum(Value[Value > 2])), by = Type]
#    Type X  Y
# 1:    A 5 24
# 2:    B 5 28
Run Code Online (Sandbox Code Playgroud)

打算向@nongkrong建议,但是他删除了,我们也可以用基数R.

aggregate(Value ~ Type, df, function(x) c(length(x), sum(x[x>2])))
#   Type Value.1 Value.2
# 1    A       5      24
# 2    B       5      28
Run Code Online (Sandbox Code Playgroud)