R语言:如何将长格式DataFrame转为单行宽格式DataFrame?
解决方案
你之前的代码问题在于:
id_cols= -c(class, sub, order)错误排除了这三个关键分组列,导致无法按class/sub/order聚合数据- 未将
time纳入列名生成逻辑,无法区分不同时间点的对应数值
可以通过以下连贯的tidyverse代码实现需求:
library(tidyverse) m=" class sub order time DV score task_type 1 1 s-c 1 ac 1 simple 1 1 s-c 1 bc 2 simple 1 1 s-c 2 ac 3 complex 1 1 s-c 2 bc 4 complex " long_data = read.table(text = m, header = TRUE) desired_output <- long_data %>% # 转换score列:将DV和time组合为新列名 pivot_wider( id_cols = c(class, sub, order), names_from = c(DV, time), names_glue = "DV_{DV}_T{time}", values_from = score ) %>% # 转换task_type列:按time拆分列 inner_join( long_data %>% distinct(class, sub, order, time, task_type) %>% pivot_wider( id_cols = c(class, sub, order), names_from = time, names_glue = "task_type_T{time}", values_from = task_type ), by = c("class", "sub", "order") ) print(desired_output)
运行后输出:
class sub order DV_ac_T1 DV_ac_T2 DV_bc_T1 DV_bc_T2 task_type_T1 task_type_T2 1 1 1 s-c 1 3 2 4 simple complex
内容的提问来源于stack exchange,提问作者Simon Harmel
相关产品推荐
相关产品推荐

