Inserting Variable length row in R for a 2D matrix -


i have data of following format

reg_no     subject   aa11     physics   aa11   chemistry   aa12     english   aa12       maths   aa12     physics 

i trying transform data row wise

physics   chemistry english       maths   physics 

i know each student can take maximum of 8 subjects

i trying create matrix can store above data variable rows (each student has different number of subjects)

i have written following code

# read csv file term4 <- read.csv("term4.csv") # find number of students matrix_length <- length(unique(term4$reg_no)) # uniquely store reg number student <- unique(term4$reg_no) # create matrix inserted csv out <- matrix(na, nrow=matrix_length , ncol=8) # max subjects = 8 ncol =8 # iterate each reg number's subjects (n in 1:matrix_length) {     y <- term4[term4[,"reg_no"] == student[n],]$subject     # transpose courses single column row , insert in matrix     out[n,] <- t(y) } 

i getting following error

error in out[n, ] <- t(y) :
    number of items replace not multiple of replacement length

could please tell me how work on error

thanks , regards

reshape() can this:

df <- data.frame(reg_no=c('aa11','aa11','aa12','aa12','aa12'), subject=c('physics','chemistry','english','maths','physics') ); reshape(transform(df,time=ave(c(reg_no),reg_no,fun=seq_along)),dir='w',idvar='reg_no'); ##   reg_no subject.1 subject.2 subject.3 ## 1   aa11   physics chemistry      <na> ## 3   aa12   english     maths   physics 

this generate data.frame many columns necessary cover subjects.

the reason code failing you've preallocated matrix 8 columns, rhs of each assignment contain many subjects current student n has in original data.frame. r rejects index-assignments target length not divisible rhs length (actually plain vectors warning, matrices seems error; regardless, it's never right thing do).


in general, if ever need carry out such non-divisible assignment, can extending rhs sufficient length appending nas. done rep() , c(), there's elegant , easy way using out-of-bounds indexing. here's demo:

m <- matrix(na_character_,2,8); m; ##      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] ## [1,] na   na   na   na   na   na   na   na ## [2,] na   na   na   na   na   na   na   na m[1,] <- letters[1:3]; ## fails; indivisible ## error in m[1, ] <- letters[1:3] : ##   number of items replace not multiple of replacement length m[2,] <- letters[1:3][1:ncol(m)]; ## works m; ##      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] ## [1,] na   na   na   na   na   na   na   na ## [2,] "a"  "b"  "c"  na   na   na   na   na 

Comments

Popular posts from this blog

twig - Using Twigbridge in a Laravel 5.1 Package -

jdbc - Not able to establish database connection in eclipse -

firemonkey - How do I make a beep sound in Android using Delphi and the API? -