使用 R pivot_longer() 从宽到长,两个内因子存储在一个变量中

问题描述

我想用两个主题内因素计算方差分析,我首先需要将文件格式从宽转换为长。这里的变量名包括 2 个不同的内因子:3 因子变量 lureType (new,sem,per) 和 2 因子变量 emotion (Neu,Neg),其值代表因变量 (falseAlarms)。

所以,我从选择相关变量开始:

long_file <- wide_file %>%
  select(ID,betweenVariable,newNeu_falseAlarm,newNeg_falseAlarm,semNeu_falseAlarm,semNeg_falseAlarm,perNeu_falseAlarm,perNeg_falseAlarm) %>% 

如果变量只包含一个因子,我会遵循这个 对于情感:

 pivot_longer(cols = c(Neg_falseAlarm,Neu_falseAlarm),names_to = "emotion",values_to = "falseAlarms")

或者对于lureType:

pivot_longer(cols = c(new_falseAlarm,sem_falseAlarm,per_falseAlarm),names_to = "lureType",values_to = "falseAlarms")

如果变量存储两个不同的因素,有人知道如何将长格式转换为宽格式吗?

TIA!

解决方法

我找到了解决方案:

pivot_longer(cols=c(newNeu_falseAlarm,newNeg_falseAlarm,semNeu_falseAlarmsemNeg_falseAlarm perNeu_falseAlarm,perNeg_falseAlarm),names_to=c("lureType","emotion"),names_sep= "N",values_to = "falseAlarms"
               )

很高兴,如果有人想添加更优雅的解决方案。我对 R 不太熟悉。