How to change column elements of a matrix for each row without creating a loop in R

I have a matrix and I would like to change the column elements from 0 to 1, vice versa, based on a vector. The first column of the first row should be switched and the 3rd column of the second row be flipped aswell. EG

mat <- matrix(c(0,1,0,0,1,0),2,3)
ind <- c(1,3)

mat1 <- matrix(c(1,1,0,0,1,1),2,3)

I would like to get mat1 from mat,

Thank you

Upvotes: 0

Views: 29

Answers (1)

akrun
akrun

Reputation: 887148

Just use row/column indexing

mat[cbind(seq_len(nrow(mat)), ind)] <- 1

Or if we don't want to modify the original object, use replace

mat1 <- replace(mat, cbind(seq_len(nrow(mat)), ind), 1)

Upvotes: 3

Related Questions