我正在准备我的数据集,以便在它上运行HLM。现在,数据集是宽格式的,所以我需要将它更改为长格式。我尝试过使用reshape函数,但到目前为止都没有效果。考试前题51题,试题后题51题.数据集的原始格式与此类似(仅针对一个个人):
Student.ID PreTest1 PreTest2 PreTest3 ... PostTest1 PostTest2 PostTest3
2322 3 2 5 2 4 5 理想情况下,我希望最后的数据集看起来如下所示:
Student.ID time Score Question
2322 1 3 1
2322 1 2 2
2322 1 5 3
2322 2 2 1
2322 2 4 2
2322 2 5 3在R中可以这样做吗?非常感谢。
发布于 2016-07-13 06:13:30
我们可以使用melt。将“data.frame”转换为“data.table”(setDT(df)),将melt从“wide”格式转换为“long”格式,然后在与变量的子字符串分组后创建“time”和“问号”变量(通过用sub删除数字部分)。
library(data.table)
melt(setDT(df), id.var = "Student.ID", value.name = "Score")[,
c("time", "Question") := .(.GRP, 1:.N) , .(sub("\\d+", "", variable))
][, variable:= NULL]
# Student.ID Score time Question
#1: 2322 3 1 1
#2: 2322 2 1 2
#3: 2322 5 1 3
#4: 2322 2 2 1
#5: 2322 4 2 2
#6: 2322 5 2 3或者使用dplyr/tidyr
library(dplyr)
library(tidyr)
gather(df, Var, Score, -1) %>%
separate(Var, into = c("time", "Var2"), sep = 3) %>%
group_by(time = match(time, unique(time))) %>%
mutate(Question = row_number()) %>%
select(-Var2)
# Student.ID time Score Question
# <int> <int> <int> <int>
#1 2322 1 3 1
#2 2322 1 2 2
#3 2322 1 5 3
#4 2322 2 2 1
#5 2322 2 4 2
#6 2322 2 5 3数据
df <- structure(list(Student.ID = 2322L, PreTest1 = 3L, PreTest2 = 2L,
PreTest3 = 5L, PostTest1 = 2L, PostTest2 = 4L, PostTest3 = 5L),
.Names = c("Student.ID",
"PreTest1", "PreTest2", "PreTest3", "PostTest1", "PostTest2",
"PostTest3"), class = "data.frame", row.names = c(NA, -1L))https://stackoverflow.com/questions/38343783
复制相似问题