[英]R - create new vectors based on elements of existing vector
and thanks in advance for your help. 并先感谢您的帮助。 I am very new to R and am having some trouble with code that, to me looks like it should work, but isn't. 我对R非常陌生,并且在代码方面遇到了一些麻烦,在我看来它应该可以工作,但事实并非如此。 I have a data frame like the one below: 我有一个像下面这样的数据框:
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
And I want it to read like this: 我希望它看起来像这样:
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
I've tried to piece together different things that I've come across and it seemed like the best approach was to create a new data frame and matrix and then populate it from the current data frame. 我尝试将遇到的不同事情组合在一起,似乎最好的方法是创建一个新的数据框和矩阵,然后从当前数据框填充它。 I came up with the broken code below: 我想出了下面的破损代码:
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]
}
}
I'm getting an error that says: 我收到一条错误消息:
the condition has length > 1 and only the first element will be used 条件的长度> 1,并且仅使用第一个元素
and I am beyond my skill level to figure it out. 我超出了我的技能水平来解决。 Any help is appreciated. 任何帮助表示赞赏。
The tidyr package can spread this long table into a wider one: tidyr程序包可以将这个长表散布成一个更大的表:
library(tidyr)
spread(classDB,classNumber,classRating,fill=NA)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.