首页 > 解决方案 > 使用汇总统计信息将虚拟变量列分成两列

问题描述

我有什么应该是一个简单的问题,但我无法弄清楚如何在 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))

引发错误,因为您不能在展开中有两个值。

标签: rdplyrtidyr

解决方案


一种选择是您将子集分成 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)

推荐阅读