重塑R中的数据矩阵

Ing*_*nga 2 casting r dataframe reshape2

我有一些要在R中重塑的数据,但不知道如何处理。这是场景:我有来自不同学校的许多学生的考试成绩数据。以下是一些示例数据:

#Create example data: 
test <- data.frame("score" = c(1,10,20,40,20), "schoolid" = c(1,1,2,2,3))
Run Code Online (Sandbox Code Playgroud)

结果是这样的数据格式:

  score schoolid
    1        1
   10        1
   20        2
   40        2
   20        3
Run Code Online (Sandbox Code Playgroud)

因此,有一个识别学校的学校ID,并且每个学生都有一个测试成绩。为了在其他程序中进行分析,我希望数据具有以下格式:

                Score student 1    Score student 2 
School ID == 1        1                   10               
School ID == 2       10                   40
School ID == 3       20                   NA
Run Code Online (Sandbox Code Playgroud)

为了重塑数据,我尝试使用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)
Run Code Online (Sandbox Code Playgroud)

我想每所学校的考试分数数量不同的事实使重组过程变得复杂。

如何重塑这些数据以及应使用哪个功能?

G. *_*eck 5

以下是一些仅使用R的底数的解决方案。所有三个解决方案均使用此新studentno变量:

studentno <- with(test, ave(schoolid, schoolid, FUN = seq_along))
Run Code Online (Sandbox Code Playgroud)

1)轻按

with(test, tapply(score, list(schoolid, studentno), c))
Run Code Online (Sandbox Code Playgroud)

给予:

   1  2
1  1 10
2 20 40
3 20 NA
Run Code Online (Sandbox Code Playgroud)

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")
Run Code Online (Sandbox Code Playgroud)

给予:

  schoolid student.1 student.2
1        1         1        10
3        2        20        40
5        3        20        NA
Run Code Online (Sandbox Code Playgroud)

3) xtabs如果没有分数为0的学生,xtabs也将起作用。

xt <- xtabs(score ~ schoolid + studentno, test)
xt[xt == 0] <- NA  # omit this step if its ok to use 0 in place of NA
xt
Run Code Online (Sandbox Code Playgroud)

给予:

        studentno
schoolid  1  2
       1  1 10
       2 20 40
       3 20   
Run Code Online (Sandbox Code Playgroud)