[Urgent]replace several rows in matrix with a vector

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

[Urgent]replace several rows in matrix with a vector

mrzung
This post has NOT been accepted by the mailing list yet.
hi all,

what i want to ask is how to replace rows with a vetor without looping.

for example, I have one matrix like this,

a<-matrix(0,100,3)

and then, I want to replace some of rows with this vector,

b<-c(1,2,3)

when I use below code, the result is what I want,

a[somerows,]<-t(b)

result of a[somerows,] is

1  2  1
2  3  2
3  1  3
1  2  1
2  3  2
3  1  3
1  2  1


actually I want this format below,

1 2 3
1 2 3
1 2 3
1 2 3
1 2 3
1 2 3

how can I solve this problem?

Thanks,
Reply | Threaded
Open this post in threaded view
|

Re: [Urgent]replace several rows in matrix with a vector

arun kirshna
Hi,
Try:
a <- matrix(0,100,3)
a1<- a
a2 <- a
somerows<- 1:5
b1<- t(replicate(length(somerows),b))
 a[somerows,]<- b1
head(a)

#or
 b2<- rep(b,each=length(somerows))
 a1[somerows,]<- b2

head(a1)
 identical(a,a1)
#[1] TRUE

 somerows2<- c(2,4,7,8,11,14)
 b3 <- rep(b,each=length(somerows2))
 a2[somerows2,] <- b3
head(a2,15)



A.K.

hi all,

what i want to ask is how to replace rows with a vetor without looping.

for example, I have one matrix like this,

a<-matrix(0,100,3)

and then, I want to replace some of rows with this vector,

b<-c(1,2,3)

when I use below code, the result is what I want,

a[somerows,]<-t(b)

result of a[somerows,] is

1  2  1
2  3  2
3  1  3
1  2  1
2  3  2
3  1  3
1  2  1


actually I want this format below,

1 2 3
1 2 3
1 2 3
1 2 3
1 2 3
1 2 3

how can I solve this problem?

Thanks,

______________________________________________
[hidden email] 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.