【问题标题】:summarise() a subset of cases with dplyrsummarise() 使用 dplyr 的案例子集
【发布时间】:2020-07-20 23:47:49
【问题描述】:

数据:

structure(list(subjnum = c(1L, 1L, 1L, 1L, 1L, 1L), expVers = structure(c(2L, 
2L, 2L, 2L, 2L, 2L), .Label = c("Angry", "Happy"), class = "factor"), 
    intendedSOA = c(1000L, 1000L, 100L, 100L, 50L, 50L), compatability = structure(c(1L, 
    1L, 1L, 1L, 1L, 1L), .Label = c("Comp", "Incomp"), class = "factor"), 
    T1RT = c(229L, 229L, 277L, 277L, 280L, 280L), T2RT = c(791L, 
    791L, 563L, 563L, 760L, 760L), T1ACC = c(1L, 1L, 1L, 1L, 
    1L, 1L), T2ACC = c(1L, 1L, 1L, 1L, 1L, 1L)), row.names = c(NA, 
6L), class = "data.frame")

我想通过它们的mean() 总结列 T1RT、T2RT、T1ACC 和 T2ACC,并通过数据中的其他变量/因素(subjnum、intendedSOA、兼容性、expVers)来组织这些值。但是,变量 T1RT 和 T2RT 的摘要不应该包括 T1ACC or T2ACC == 0 的试验,但变量 T1ACC 和 T2ACC 的摘要应该包括所有值(无条件求和) .我尝试通过执行以下操作在summarise() 中包含if() 参数:

> backcomplong2 <- ACC %>%
+   select(subjnum, expVers,intendedSOA, compatability, T1RT, T2RT, T1ACC, T2ACC)%>%
+   group_by(subjnum, compatability, expVers, intendedSOA)%>%
+   summarise(T1RT = if(T1ACC == 1 && T2ACC == 1) round(mean(T1RT)), 
+             T2RT = if(T1ACC == 1 && T2ACC == 1) round(mean(T2RT)),
+             T1ACC = mean(T1ACC), 
+             T2ACC = mean(T2ACC))

但收到此错误:

Problem with `summarise()` input `T1RT`.
x Input `T1RT` must be a vector, not NULL.
i Input `T1RT` is `if (T1ACC == 1 && T2ACC == 1) round(mean(T1RT))`.
i The error occured in group 14: subjnum = 3, compatability = "Comp", expVers = "Happy", intendedSOA = 100.

****** 请注意,我的可重现数据不会返回相同的错误 ********
较大的数据(我没有在此处提供,因为它太大而无法使用 dput() 粘贴到此问题中)返回错误。

我认为我错误地使用了if() 语句,也许我可以尝试使用if_else() 代替?另一种解决方法是简单地执行两次summarise(),一次用于 RT,另一次用于 ACC,但这更简洁。

【问题讨论】:

    标签: r dplyr tidyverse


    【解决方案1】:

    您输入if 来检查条件,但不要输入else 并告诉条件不满足时需要做什么。因此,它返回一个导致错误的NULL 对象。

    这里不需要if/else,但如果您只对那些您想采用mean 的值进行子集化。试试这个:

    library(dplyr)
    
    ACC %>%
       group_by(subjnum, compatability, expVers, intendedSOA)%>%
       summarise(T1RT = mean(T1RT[T1ACC == 1 & T2ACC == 1]), 
                 T2RT =  mean(T2RT[T1ACC == 1 & T2ACC == 1]),
                 T1ACC = mean(T1ACC), 
                 T2ACC = mean(T2ACC))
    

    【讨论】:

    • 很简单,非常感谢!您的解决方案只是 T1RT 的子集。
    猜你喜欢
    • 2022-01-23
    • 1970-01-01
    • 2015-10-27
    • 2016-08-07
    • 2019-11-27
    • 1970-01-01
    • 2020-01-21
    • 1970-01-01
    • 2018-04-30
    相关资源
    最近更新 更多