curbholes
curbholes

Reputation: 557

Replace certain elements in a list of matrices with equal structure

I have a list of several matrices which all have the same 11*19 structure but different values in them. In each of those matrices I want to replace the values in certain elements with "NA".
It is working for one single matrix:

m1<-matrix(seq(1:209),11,19)

m1[1,1:19]<-NA
m1[11,1:19]<-NA
m1[1:11,1]<-NA
m1[1:11,19]<-NA
m1[2,1:5]<-NA
m1[2,15:19]<-NA
m1[10,1:5]<-NA
m1[10,15:19]<-NA
m1[3,1:4]<-NA
m1[3,16:19]<-NA
m1[9,1:4]<-NA
m1[9,16:19]<-NA
m1[4,1:3]<-NA
m1[4,17:19]<-NA
m1[8,1:3]<-NA
m1[8,17:19]<-NA
m1[5,1:2]<-NA
m1[5,18:19]<-NA
m1[7,1:2]<-NA
m1[7,18:19]<-NA

It is not working anymore if I want to do this to a list of matrices:

m2<-matrix(seq(209,1,by=-1),11,19)
m3<-matrix(seq(210,418,by=1),11,19)
m_list<-list(m1,m2,m3)

m_list[1,1:19]<-NA
m_list[11,1:19]<-NA
m_list[1:11,1]<-NA
m_list[1:11,19]<-NA
m_list[2,1:5]<-NA
m_list[2,15:19]<-NA
m_list[10,1:5]<-NA
m_list[10,15:19]<-NA
m_list[3,1:4]<-NA
m_list[3,16:19]<-NA
m_list[9,1:4]<-NA
m_list[9,16:19]<-NA
m_list[4,1:3]<-NA
m_list[4,17:19]<-NA
m_list[8,1:3]<-NA
m_list[8,17:19]<-NA
m_list[5,1:2]<-NA
m_list[5,18:19]<-NA
m_list[7,1:2]<-NA
m_list[7,18:19]<-NA

Is it feasible with apply or a related function?

Upvotes: 1

Views: 388

Answers (1)

akrun
akrun

Reputation: 887048

With list we can use lapply

lapply(m_list, function(x) {x[1, 1:19] <- NA
                            x[11, 1:19] <- NA 
                            x
             })

NOTE: We can use most of the assignments as showed in the OP's code.

Upvotes: 1

Related Questions