[R] matrix problem-replacing pieces of a matrix

Costis Ghionnis conighion at gmail.com
Tue Jun 21 13:16:55 CEST 2011


#Hallo again.. Thank you for your answers. To sum up:

#The problem was that we have the matrix m
m<-matrix(numeric(length=5*4),nrow=5,ncol=4)
m

#      [,1] [,2] [,3] [,4]
# [1,]    0    0    0    0
# [2,]    0    0    0    0
# [3,]    0    0    0    0
# [4,]    0    0    0    0
# [5,]    0    0    0    0

#and a vector y
y<-c(1,1,1,3,3)

#y has informations about the rows of m,
#and we wanted to change the rows that correspond to y==1
#with the vector c(1,2,3,4). The most intuitive procedure didn't work

m[y==1,1:4]<-c(1,2,3,4)
m

#      [,1] [,2] [,3] [,4]
# [1,]    1    4    3    2
# [2,]    2    1    4    3
# [3,]    3    2    1    4
# [4,]    0    0    0    0
# [5,]    0    0    0    0

#because the matrix is being filled by column. The second thought was to
#work with the transpose matrix.

m_temp<-t(m)
m_temp[1:4,y==1]<-c(1,2,3,4)

m<-t(m_temp)


#R assigns to an object another object of the same class. So the other 
way proposed
#by Sara is to to assign to the submatrix
m[y==1,]
#of m another matrix
matrix(1:4,nrow=sum(y==1),ncol=ncol(m),byrow=T)

#That is:
m[y==1,]<-matrix(1:4,nrow=sum(y==1),ncol(m),byrow=T)
m
#      [,1] [,2] [,3] [,4]
# [1,]    1    2    3    4
# [2,]    1    2    3    4
# [3,]    1    2    3    4
# [4,]    0    0    0    0
# [5,]    0    0    0    0

#The last way to do this was proposed by David, Patric and it is discussed
#in Circle 8 (8.3.25--replacing pieces of a matrix) of R-inferno book.
m[y==1,1:4]<-rep(c(1,2,3,4),each=sum(y==1))



More information about the R-help mailing list