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:
如果其它矩阵的值满足某些条件,我就尝试对矩阵中的元素进行运算。我知道如何使用一个for循环使用行和列来解决它,但我确信在r中有更有效的方法来解决它。
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 }
2 个解决方案
#1
2
Here's a pretty straightforward way. Use a named vector to set your conditions.
这是一个非常简单的方法。使用命名向量来设置条件。
First, here's the data I'm working with:
首先,这是我正在研究的数据:
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"
Second, the solution in one nice compact line.
第二,解决方案在一个紧凑的线条。
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
Basically, the c(a = 10, b = -10, c = 0)[cond]
uses your "cond" matrix to create a vector that you can use to multiply your original matrix by.
基本上,c(a = 10, b = -10, c = 0)[cond]使用你的“cond”矩阵来创建一个向量,你可以用它乘以你的原始矩阵。
#2
2
You could try this:
你可以试试这个:
m[conda] <- m[conda <- cond == 'a'] * 10
m[condb] <- m[condb <- cond == 'b'] * -10
m[!conda & !condb] <- 0
#1
2
Here's a pretty straightforward way. Use a named vector to set your conditions.
这是一个非常简单的方法。使用命名向量来设置条件。
First, here's the data I'm working with:
首先,这是我正在研究的数据:
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"
Second, the solution in one nice compact line.
第二,解决方案在一个紧凑的线条。
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
Basically, the c(a = 10, b = -10, c = 0)[cond]
uses your "cond" matrix to create a vector that you can use to multiply your original matrix by.
基本上,c(a = 10, b = -10, c = 0)[cond]使用你的“cond”矩阵来创建一个向量,你可以用它乘以你的原始矩阵。
#2
2
You could try this:
你可以试试这个:
m[conda] <- m[conda <- cond == 'a'] * 10
m[condb] <- m[condb <- cond == 'b'] * -10
m[!conda & !condb] <- 0