首页 > 解决方案 > dplyr 正确使用收集功能

问题描述

应该有一个使用 ddplyr 收集功能的明显解决方案,但说我有一张桌子

   condition  learnedtogether same_block same_session      mean
1               1           FALSE      FALSE        FALSE 0.8309669
2               1           FALSE      FALSE         TRUE 0.8051708
3               1            TRUE       TRUE         TRUE 0.8681102
4               2           FALSE      FALSE        FALSE 0.8188932
5               2           FALSE      FALSE         TRUE 0.7697297
6               2            TRUE       TRUE         TRUE 0.8899083
7               3           FALSE      FALSE        FALSE 0.8742560
8               3           FALSE       TRUE         TRUE 0.8915900
9               3            TRUE       TRUE         TRUE 0.8927894

如何收集数据以便我有 3 列

condition   LearningType      mean
1             learnedtogether   .86
1             same session       .8
1             different Session .83

在一起学习的地方,same_block 和same_session 都折叠成一行。

提前致谢。

标签: rdplyr

解决方案


如果顺序重复(例如,第一个值 incondition的值应该是"different Session"in column LearningType,第二个值 incondition的值应该是"same Session"in column LearningType),那么您可以利用数据帧将回收与长度不同的原子向量的值这一事实数据框中的行数:

df$LearningType <- c("different Session", "same session", "learnedtogether")
df[,-(2:4)]

输出

  condition      mean      LearningType
1         1 0.8309669 different Session
2         1 0.8051708      same session
3         1 0.8681102   learnedtogether
4         2 0.8188932 different Session
5         2 0.7697297      same session
6         2 0.8899083   learnedtogether
7         3 0.8742560 different Session
8         3 0.8915900      same session
9         3 0.8927894   learnedtogether

否则,您可以rowSum使用逻辑列并像这样使用它们:

library(dplyr)

v <- c("different Session", "same session", "?", "learnedtogether")

df %>% 
  mutate(LearningType = v[as.numeric(ordered((rowSums(.[2:4]))))]) %>% 
  select(-(learnedtogether:same_session))

尽管从您的问题中不清楚何时做什么same_block以及same_session是该行中的唯一TRUE值。

输出

  condition      mean      LearningType
1         1 0.8309669 different Session
2         1 0.8051708      same session
3         1 0.8681102   learnedtogether
4         2 0.8188932 different Session
5         2 0.7697297      same session
6         2 0.8899083   learnedtogether
7         3 0.8742560 different Session
8         3 0.8915900                 ?
9         3 0.8927894   learnedtogether

数据

df <- structure(list(condition = c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 
3L), learnedtogether = c(FALSE, FALSE, TRUE, FALSE, FALSE, TRUE, 
FALSE, FALSE, TRUE), same_block = c(FALSE, FALSE, TRUE, FALSE, 
FALSE, TRUE, FALSE, TRUE, TRUE), same_session = c(FALSE, TRUE, 
TRUE, FALSE, TRUE, TRUE, FALSE, TRUE, TRUE), mean = c(0.8309669, 
0.8051708, 0.8681102, 0.8188932, 0.7697297, 0.8899083, 0.874256, 
0.89159, 0.8927894)), row.names = c(NA, -9L), class = "data.frame")

推荐阅读