在此先感谢您的帮助。我对R很陌生,并且在代码方面遇到了一些麻烦,在我看来它应该可以工作,但事实并非如此。我有一个像下面这样的数据框:
studentID classNumber classRating
7 1 4
7 2 4
7 4 3
79 1 5
79 2 3
116 1 5
116 2 4
134 1 5
134 3 5
134 4 5
我希望它看起来像这样:
Student ID class1 class2 class3 class4
7 4 4 NA 3
79 5 3 NA NA
116 5 4 NA NA
134 5 NA 5 5
我尝试将遇到的不同事情组合在一起,似乎最好的方法是创建一个新的数据框和矩阵,然后从当前数据框填充它。我想出了下面的破损代码:
classRatings = data.frame(matrix(NA,4,5))
for(i in 1:nrow(classDB)){
#Find ratings by each student
rowsToReplace = classDB$studentID==classRatings$studentID[i]
#Make a row for each unique studentID in classRatings
classDB$studentID[rowsToReplace] = classRatings$studentID[i]
#for each studentID, find put the given rating for each unique class into
#it's own vector
for(j in classDB$classNumber){
if(classDB$classNumber==1){classRatings$class1==classDB$classRating}[j]
if(classDB$classNumber==2){classRatings$class2==classDB$classRating}[j]
if(classDB$classNumber==3){classRatings$class3==classDB$classRating}[j]
if(classDB$classNumber==4){classRatings$class4==classDB$classRating}[j]
if(classDB$classNumber==5){classRatings$class5==classDB$classRating}[j]
}
}
我收到一条错误消息:
条件的长度> 1,并且仅使用第一个元素
而且我超出了我的技能水平,无法弄清楚。任何帮助表示赞赏。
该tidyr包可以传播这个长条桌到更广泛的一种:
library(tidyr)
spread(classDB,classNumber,classRating,fill=NA)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句