如何转换DataFrame:将类别列拆分为多列,日期作为唯一行展示频次
解决方案
你目前的代码已经完成了按日期和情绪类型分组汇总频次的操作,但还没完成长格式转宽格式的关键一步——这就是你没得到预期输出的原因。只需要在现有代码后添加pivot_wider(tidyverse现在更推荐用这个替代spread),就能实现把每种情绪(anger、sadness等)转为单独列、每个日期占一行的需求。
完整代码如下:
library(dplyr) library(tidyr) # 加载tidyr包以使用pivot_wider filteredemotion2 <- filteredemotion1 %>% arrange(timestamp) %>% filter(emotion_count > 0) %>% group_by(date, emotion_type) %>% summarise(Emotion_Count = sum(emotion_count), .groups = "drop") %>% # 移除分组状态,避免后续警告 pivot_wider( names_from = emotion_type, # 把emotion_type的取值作为列名 values_from = Emotion_Count, # 用汇总后的频次填充对应列 values_fill = 0 # 无数据的日期-情绪组合填充0,可选 )
关键说明:
.groups = "drop":分组汇总后清除分组标记,防止后续操作出现不必要的警告pivot_wider参数:names_from指定要转为列的字段(这里是emotion_type)values_from指定填充列内容的字段(这里是汇总后的Emotion_Count)values_fill = 0可选,如果不想让无数据的单元格显示NA,就用0填充
要是你更习惯用旧版的spread函数,替换成下面这行也可以:
spread(key = emotion_type, value = Emotion_Count, fill = 0)
内容的提问来源于stack exchange,提问作者Imafont
相关产品推荐
相关产品推荐

