r - 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 都折叠成一行。
提前致谢。
解决方案
如果顺序重复(例如,第一个值 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")
推荐阅读
- javascript - 如何使用鼠标滚轮和带有自定义导航的 MAC 触控板滑动 owl carousel 滑块和光滑滑块?
- machine-learning - 数据集不平衡,大小限制为 60mb,电子邮件分类
- java - 我无法将我的对象主体发送到有角度的两个输入字段中
- laravel - laravel 中的以下代码发送卖家(没有身份验证)邮件不起作用
- github - PyCharm 无法“从版本控制中签出”
- laravel-5 - 如何在 TDD 测试中运行 delete 方法?
- c# - 使我的 WinForms 应用程序在使用 Console.WriteLine() 时表现得像控制台应用程序一样
- python - 找不到 pip 包
- docker - 单节点 Kubernetes 集群上的 HPA 实现
- r - 使用officeR在闪亮中生成word报告