r - 使用汇总统计信息将虚拟变量列分成两列
问题描述
我有什么应该是一个简单的问题,但我无法弄清楚如何在 dplyr/tidyr 中实现所需的结果。
我刚刚计算了一个汇总数据框,如下所示:
results <- df_long %>%
group_by(question,imputed_liberal, question_text) %>%
summarize(Accuracy = mean(score, na.rm = T), Reaction_Time = mean(reation_time, na.rm = T), Number = n())
每个问题在两行中重复,一列用于 imputed_liberal = T,另一行用于 imputed_liberal = F,列用于准确性和反应时间。
question imputed_liberal question_text Accuracy Reaction_Time Number
1 10 F How many... 0.750 61.4 16
2 10 T How many... 0.429 55.9 14
我想将这两行合并为一行(每个问题一行),其中包含“保守准确性”(推算自由主义 = F)、“自由主义准确性”、“保守反应时间”和“自由反应时间”列。
我认为这spread
是正确的方法,但无法弄清楚如何传播两个值(准确性和反应时间)。
我的尝试:
results <- results %>%
filter(!is.na(Accuracy)) %>%
spread(results, key = imputed_liberal, value = c(Accuracy, Reaction_time))
引发错误,因为您不能在展开中有两个值。
解决方案
一种选择是您将子集分成 2 个部分并将这 2 个部分连接在一起。
library(dplyr)
inner_join(filter(results, imputed_liberal),
filter(results, !imputed_liberal), by="question") %>%
select(-Number.y)
结果:
注意:可以根据自己的选择重命名列。
# question imputed_liberal.x question_text.x Accuracy.x Reaction_Time.x Number.x imputed_liberal.y question_text.y Accuracy.y Reaction_Time.y
# 1 10 TRUE How many... 0.429 55.9 14 FALSE How many... 0.75 61.4
数据:
results <- read.table(text =
"question imputed_liberal question_text Accuracy Reaction_Time Number
1 10 FALSE 'How many...' 0.750 61.4 16
2 10 TRUE 'How many...' 0.429 55.9 14",
header = TRUE, stringsAsFactors = FALSE)
推荐阅读
- node.js - TypeError:无法读取未定义的属性“basename”
- sqlite - 表 2 中不存在表 1 中的行的两个表中的 sql 行数
- javascript - oidc-client 从本地主机或其他 URL 配置发现文档
- angular - Angular 8嵌套FormBuilder找不到控件
- django - Django/Apache - 从网络驱动器读取文件 (Windows)
- python-3.x - 来自 pynput 的侦听器阻塞 on_press 中的函数,直到它结束运行
- haskell - 堆栈构建失败并出现 LLD 错误
- asp.net-core - ASP NET Core Web API 返回指向图像的链接失败
- python - 过滤外键项
- linux - 用 cmp 和 find 比较本地和 ftp 文件