Two solutions... v + matrix(b, nrow(v), ncol(v), byrow = TRUE)
or t(apply(v, 1, `+`, b)) Peter On Sun, May 22, 2016 at 10:39 PM, Steven Yen <sye...@gmail.com> wrote: > Hi all, need help below. Thank you. > > > # Matrix v is 5 x 3 > > # Vector b is of length 3 > > # I like to add b[1] to all element in v[,1] > > # I like to add b[2] to all element in v[,2] > > # I like to add b[3] to all element in v[,3] > > # as follows > > v<-matrix(0,nrow=5,ncol=3); v > [,1] [,2] [,3] > [1,] 0 0 0 > [2,] 0 0 0 > [3,] 0 0 0 > [4,] 0 0 0 > [5,] 0 0 0 > > b<-c(0.1,0.2,0.3) > > cbind( > + (b[1]+v[,1]), > + (b[2]+v[,2]), > + (b[3]+v[,3])) > [,1] [,2] [,3] > [1,] 0.1 0.2 0.3 > [2,] 0.1 0.2 0.3 > [3,] 0.1 0.2 0.3 > [4,] 0.1 0.2 0.3 > [5,] 0.1 0.2 0.3 > > # I am obviously not using sapply correctly: > > as.data.frame(sapply(b,"+",v)) > V1 V2 V3 > 1 0.1 0.2 0.3 > 2 0.1 0.2 0.3 > 3 0.1 0.2 0.3 > 4 0.1 0.2 0.3 > 5 0.1 0.2 0.3 > 6 0.1 0.2 0.3 > 7 0.1 0.2 0.3 > 8 0.1 0.2 0.3 > 9 0.1 0.2 0.3 > 10 0.1 0.2 0.3 > 11 0.1 0.2 0.3 > 12 0.1 0.2 0.3 > 13 0.1 0.2 0.3 > 14 0.1 0.2 0.3 > 15 0.1 0.2 0.3 > > > [[alternative HTML version deleted]] > > ______________________________________________ > R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see > 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. ______________________________________________ R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see 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.