【发布时间】:2020-06-19 09:19:36
【问题描述】:
我想将数据集从宽格式重塑为长格式。
数据集包含 300 个变量,每个变量都以原理命名:ModelID_Emotion_ModelGender。以下示例数据:
df <- structure(list(X71_Anger_Male = structure(c(3L, 1L, 2L), .Label = c("Anger",
"Disgust", "Fear"), class = "factor"), X71_Disgus_Male = structure(c(2L,
1L, 1L), .Label = c("Disgust", "Fear"), class = "factor")), class = "data.frame", row.names = c(NA,
-3L))
看起来像
X71_Anger_Male X71_Disgus_Male
1 Fear Fear
2 Anger Disgust
3 Disgust Disgust
我想以将列名中的信息获取并放入新变量的方式转置数据。例如,应该有一个新变量ModelGender,一个新变量modelID和一个新变量emotion。所以数据集应该是这样的:
desired <- structure(list(Gender = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "Male", class = "factor"),
ModelNumber = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "X71", class = "factor"),
Emotion = structure(c(2L, 2L, 2L, 1L, 1L, 1L), .Label = c("Anger",
"Disgust"), class = "factor"), Response = structure(c(3L,
2L, 2L, 3L, 1L, 2L), .Label = c("Anger", "Disgust", "Fear"
), class = "factor")), class = "data.frame", row.names = c(NA,
-6L))
应该是这样的
Gender ModelNumber Emotion Response
1 Male X71 Disgust Fear
2 Male X71 Disgust Disgust
3 Male X71 Disgust Disgust
4 Male X71 Anger Fear
5 Male X71 Anger Anger
6 Male X71 Anger Disgust
当我使用 reshape、gather/spread 或 melt/cast 时,它不会给出预期的结果。有没有人知道如何做到这一点?
感谢您的宝贵时间!
【问题讨论】:
标签: r