I'm trying to performed operations by element in a matrix if the values of other matrix meet some criteria. I know how to solve it with a for
loop using rows and columns but I'm sure that there are more efficient ways to do it in R. I have tried with apply(...,c(1,2),FUN)
but don't know how to go over the elements of cond
to check its values:
m <- matrix(rnorm(9),3,3)
cl <- c('a','b','c')
cond <- matrix(sample(cl,9,replace=T),3,3)
res.m <- apply(m, c(1,2), function(x) if (cond == 'a' ) { x*10 } if (cond == 'b' ) { x*-10 } else { 0 }