Thuy Hang Duong
Thuy Hang Duong

Reputation: 1

How to assign multiple values for a matrix in R?

I have a 93060-by-141 matrix file with filled values. I need to assign zeros to some rows and columns with the condition: Row 1: 65 of column 1; row 67:131 of column 2; row 133:197 of column 3 and so on. This condition excludes for some column, i.e the values in rows of column 10,20,36 are unchanged.

I think I will need a For-loop. But I have no idea how to code for the link of rows and columns expressing the mentioned condition.

Upvotes: 0

Views: 537

Answers (1)

DaveArmstrong
DaveArmstrong

Reputation: 21982

You can change multiple values by providing a matrix of indexes to a matrix. The indices correspond with the row (first column) and column (second column) numbers of the cells. For example doing mymat[cbind(1:10, 1)] <- 0 would change the first through tenth rows of column 1 to zero. In you case, you could put together several such cbind() statements with a call to rbind(). For example, mymat[rbind(cbind(1:5, 1), cbind(6:10, 2))] <- 0 would change the first through fifth rows of column 1 and the sixth through tenth rows of column 2 to zero. In the example you proposed above, it would be something like this:

my_mat[rbind(
  cbind(1:65, 1), 
  cbind(67:131, 2),
  cbind(133:197,3))] <- 0 

Upvotes: 2

Related Questions