R中数据矩阵的整形
我在R中有一些数据需要重新塑造,但我不知道如何重塑。下面是一个场景:我有来自不同学校的一些学生的考试成绩数据。以下是一些示例数据:R中数据矩阵的整形,r,casting,dataframe,reshape2,R,Casting,Dataframe,Reshape2,我在R中有一些数据需要重新塑造,但我不知道如何重塑。下面是一个场景:我有来自不同学校的一些学生的考试成绩数据。以下是一些示例数据: #Create example data: test <- data.frame("score" = c(1,10,20,40,20), "schoolid" = c(1,1,2,2,3)) 因此,有一个学校id来识别学校,每个学生都有一个考试分数。对于不同程序中的分析,我希望数据的格式如下: score schoolid 1 1
#Create example data:
test <- data.frame("score" = c(1,10,20,40,20), "schoolid" = c(1,1,2,2,3))
因此,有一个学校id来识别学校,每个学生都有一个考试分数。对于不同程序中的分析,我希望数据的格式如下:
score schoolid
1 1
10 1
20 2
40 2
20 3
Score student 1 Score student 2
School ID == 1 1 10
School ID == 2 10 40
School ID == 3 20 NA
为了重塑数据,我尝试使用重塑2库中的重塑和强制转换函数,但这导致了错误:
#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)
我想,每所学校的考试分数不同,这一事实使重组过程复杂化
如何重塑此数据以及应使用哪个函数 您必须在某个地方定义学生id,例如:
test <- data.frame("score" = c(1,10,20,40,20), "schoolid" = c(1,1,2,2,3))
test$studentid <- c(1,2,1,2,1)
library(reshape2)
dcast(test, schoolid ~ studentid, value.var="score",mean)
schoolid 1 2
1 1 1 10
2 2 20 40
3 3 20 NaN
test以下是一些仅使用R的基数的解决方案。所有三个解决方案都使用这个新的studentno
变量:
studentno <- with(test, ave(schoolid, schoolid, FUN = seq_along))
给予:
1 2
1 1 10
2 20 40
3 20 NA
schoolid student.1 student.2
1 1 1 10
3 2 20 40
5 3 20 NA
studentno
schoolid 1 2
1 1 10
2 20 40
3 20
2)重塑
# rename score to student and append studentno column
test2 <- transform(test, student = score, score = NULL, studentno = studentno)
reshape(test2, dir = "wide", idvar = "schoolid", timevar = "studentno")
3)如果没有得分为0的学生,xtabsxtabs
也可以工作
xt <- xtabs(score ~ schoolid + studentno, test)
xt[xt == 0] <- NA # omit this step if its ok to use 0 in place of NA
xt
您必须在data.frame上定义学生id。
studentno
schoolid 1 2
1 1 10
2 20 40
3 20