Mathica
Mathica

Reputation: 1303

a loop to add a row to a vector in R

I want to get something like:
1 1 1
1 1 1
1 1 1
of course 1 is not my value. but just as an example to ask my question.

my.vec <- c(1,1,1)
for(i in 1:3){
 my.vec <-  rbind( my.vec , my.vec )}

this obviously does not do what I want, it gives many more rows. how can I add a row to my current vector at each iteration of the for loop.

Upvotes: 1

Views: 307

Answers (1)

akrun
akrun

Reputation: 887213

We can use replicate

replicate(3, my.vec)

-ouptut

      [,1] [,2] [,3]
[1,]    1    1    1
[2,]    1    1    1
[3,]    1    1    1

In the OP's code, we can change it to

out <- c()
for(i in 1:3){
 out <-  rbind(out , my.vec )
}

Upvotes: 1

Related Questions