【发布时间】:2014-03-12 14:53:38
【问题描述】:
我有一些数据要在 R 中重塑,但不知道如何。这是场景:我有来自不同学校的许多学生的考试成绩数据。以下是一些示例数据:
#Create example data:
test <- data.frame("score" = c(1,10,20,40,20), "schoolid" = c(1,1,2,2,3))
产生这样的数据格式:
score schoolid
1 1
10 1
20 2
40 2
20 3
因此,有一个学校 ID 可以标识学校,并且每个学生都有一个考试成绩。对于不同程序中的分析,我希望数据格式如下:
Score student 1 Score student 2
School ID == 1 1 10
School ID == 2 10 40
School ID == 3 20 NA
为了重塑数据,我尝试使用 reshape2 库中的 reshape 和 cast 函数,但这导致了错误:
#Reshape function
reshape(test, v.names = test2$score, idvar = test2$schoolid, direction = "wide")
reshape(test, idvar = test$schoolid, direction = "wide")
#Error: in [.data.frame'(data,,idvar): undefined columns selected
#Cast function
cast(test,test$schoolid~test$score)
#Error: Error: could not find function "cast" (although ?cast works fine)
我想,每所学校的考试成绩数量不同,这一事实使重组过程变得复杂。
我如何重塑这些数据以及我应该使用哪个函数?
【问题讨论】:
-
你必须在data.frame上定义学生ID。
标签: r casting dataframe reshape2