[R] qoestion on insert a vector into a matrix
jim holtman
jholtman at gmail.com
Sun Mar 7 00:45:13 CET 2010
Try this:
> x <- matrix(0,10,5)
> vecToAdd <- 1:5
> # add to rows 1,4,8,9
> # need to transpose because of the way matrix is filled
> # this does not give the right result
> x[c(1,4,8,9),] <- vecToAdd
> x
[,1] [,2] [,3] [,4] [,5]
[1,] 1 5 4 3 2
[2,] 0 0 0 0 0
[3,] 0 0 0 0 0
[4,] 2 1 5 4 3
[5,] 0 0 0 0 0
[6,] 0 0 0 0 0
[7,] 0 0 0 0 0
[8,] 3 2 1 5 4
[9,] 4 3 2 1 5
[10,] 0 0 0 0 0
> x <- matrix(0,10,5) # refresh
> x <- t(x)
> x[, c(1,4,8,9)] <- vecToAdd # note adding to columns now
> t(x) # put in back in the right orientation
[,1] [,2] [,3] [,4] [,5]
[1,] 1 2 3 4 5
[2,] 0 0 0 0 0
[3,] 0 0 0 0 0
[4,] 1 2 3 4 5
[5,] 0 0 0 0 0
[6,] 0 0 0 0 0
[7,] 0 0 0 0 0
[8,] 1 2 3 4 5
[9,] 1 2 3 4 5
[10,] 0 0 0 0 0
>
>
On Sat, Mar 6, 2010 at 12:21 PM, <khazaei at ceremade.dauphine.fr> wrote:
> Hi,
> I want to add a vector many time to rows of the matrix without use the loop.
> could you please hint me?
> thanks
> khazei
>
> ______________________________________________
> R-help at r-project.org 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.
>
--
Jim Holtman
Cincinnati, OH
+1 513 646 9390
What is the problem that you are trying to solve?
More information about the R-help
mailing list