简体   繁体   中英

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. 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

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:

library(tidyr)
spread(classDB,classNumber,classRating,fill=NA)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM