On Tue, 2007-04-10 at 21:19 -0400, John Sorkin wrote: > R 2.4.1 > windows XP > > I am trying to fill in a matrix with binomial probabilities without > using a for loop. I am trying to obtain a value for pbinom using the > value stored in column one of the matrix delete. Clearly I am doing > something wrong. Please help me understand my error. > > > delete<-matrix(nrow=31,ncol=2) > > delete[1:31,1]<-1:31 > > delete[,2]<-sapply(delete[,2], pbinom,delete[,1],30,0) > Error in delete[, 2] <- sapply(delete[, 2], pbinom, delete[, 1], 30, > 0) : > number of items to replace is not a multiple of replacement > length > > Thanks, > John
John, You have a vector (delete[, 1]) being passed to pbinom(). Thus for each value in delete[, 2], pbinom() is returning a vector containing 31 elements: > str(pbinom(delete[, 1], 30, 0)) num [1:31] 1 1 1 1 1 1 1 1 1 1 ... By using sapply() in the way you are above, you are essentially getting a double vectorized process with a result of: > str(sapply(delete[,2], pbinom, delete[, 1], 30, 0)) num [1:31, 1:31] NA NA NA NA NA NA NA NA NA NA ... That is, a 31 x 31 matrix as a result and you are trying to assign that result to the 31 elements in the second column of delete. All you really need (since pbinom() is already vectorized) is: > pbinom(delete[, 1], 30, 0) [1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 Presuming that this is end result that you seek. HTH, Marc Schwartz ______________________________________________ [email protected] mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
