3

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 }
4

2 回答 2

2

这是一个非常简单的方法。使用命名向量来设置条件。

首先,这是我正在使用的数据:

set.seed(1)
m <- matrix(rnorm(9),3,3)
cl <- c('a','b','c')
cond <- matrix(sample(cl,9,replace=T),3,3)
m
#            [,1]       [,2]      [,3]
# [1,] -0.6264538  1.5952808 0.4874291
# [2,]  0.1836433  0.3295078 0.7383247
# [3,] -0.8356286 -0.8204684 0.5757814

cond
#      [,1] [,2] [,3]
# [1,] "b"  "a"  "a" 
# [2,] "c"  "b"  "b" 
# [3,] "c"  "a"  "a"

其次,在一条漂亮的紧凑线中解决方案。

m * c(a = 10, b = -10, c = 0)[cond]
#          [,1]      [,2]      [,3]
# [1,] 6.264538 15.952808  4.874291
# [2,] 0.000000 -3.295078 -7.383247
# [3,] 0.000000 -8.204684  5.757814

基本上,c(a = 10, b = -10, c = 0)[cond]使用你的“cond”矩阵来创建一个向量,你可以用它来乘以你的原始矩阵。

于 2013-09-06T09:55:10.647 回答
2

你可以试试这个:

m[conda] <- m[conda <- cond == 'a'] * 10
m[condb] <- m[condb <- cond == 'b'] * -10
m[!conda & !condb] <- 0
于 2013-09-06T09:03:00.040 回答