如果符合R中的条件,则执行算术矩阵运算符

时间:2018-06-05 18:43:31

标签: r for-loop if-statement operators logical-operators

我有三个矩阵(忽略这些值,它们仅用于说明)。 abc具有相同的变量(它们具有相同的列/变量和“定位”,但衡量的是不同的东西)

# my actual mat is 120x80
a = rbind(c(1,1,2,3,1), c(2,2,3,1,2), c(3,3,1,2,1)) 
a
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    1    2    3    1
[2,]    2    2    3    1    2
[3,]    3    3    1    2    1

# my actual mat is 120x80    
b = rbind(c(0.8,0.6,0.7,0.8,0.9), c(0.6,0.7,0.8,0.7,0.6), c(0.8,0.9,0.7,0.6,0.9))
b
     [,1] [,2] [,3] [,4] [,5]
[1,]  0.8  0.6  0.7  0.8  0.9
[2,]  0.6  0.7  0.8  0.7  0.6
[3,]  0.8  0.9  0.7  0.6  0.9

# my actual mat 120x80
c = rbind(c(0.1,0.1,0.3,0.2,0.1), c(0.3,0.2,0.1,0.2,0.1), c(0.2,0.3,0.1,0.2,0.3))
c
     [,1] [,2] [,3] [,4] [,5]
[1,]  0.1  0.1  0.3  0.2  0.1
[2,]  0.3  0.2  0.1  0.2  0.1
[3,]  0.2  0.3  0.1  0.2  0.3

我们从b获取行,从c

获取行
If 1 in a[1,] then b[1,]-c[1,], else -c[1,]
If 2 in a[1,] then b[1,]-c[1,], else -c[1,]    or simply 0-c[1,]
If 3 in a[1,] then b[1,]-c[1,], else -c[1,]

d.row1 (a 3x80 matrix)
rownames(drow1)<-c("1","2","3")
  [,1] [,2] [,3] [,4] [,5]
1  0.7  0.5 -0.3 -0.2  0.8
2 -0.1 -0.1  0.4 -0.2 -0.1
3 -0.1 -0.1 -0.3  0.6 -0.1

请注意,d.row1[1,1]d.row1[1,2]d.row1[1,5]a[1,]中的分类为1,而第1行中的其他值的值为2或3.因此,我们执行了操作b[1,]-c[1,]而不是-c[1,]

看起来像这样:

enter image description here

同样,对于行a[2,]

If 1 in a[2,] then b[2,]-c[2,], else -c[2,]
If 2 in a[2,] then b[2,]-c[2,], else -c[2,]    or simply 0-c[2,]
If 3 in a[2,] then b[2,]-c[2,], else -c[2,]

d.row2 (a 3x80 matrix)
  [,1] [,2] [,3] [,4] [,5]
1 -0.3 -0.2 -0.1  0.5 -0.1
2  0.3  0.5 -0.1 -0.2  0.5
3 -0.3 -0.2  0.7 -0.2 -0.1

请注意,d.row1d.row2分别来自abc的第1行和第2行。

我想为abc中的每一行创建一个列表。总共120个数据帧在一个列表中(因为我在其他矩阵中有120行)。

我认为for循环或类似可能对我的问题有用。

提前致谢!

1 个答案:

答案 0 :(得分:2)

您可以使用(a的第1行)

计算您的基本操作
d.row1 <-  b[rep(1, 3), ] * outer(1:3, a[1,], "==") - c[rep(1, 3), ]

列表可以使用lapply完成 - 其他选项不会为正确的输入/输出提供选项(tapply需要向量输入,apply仅允许矩阵输出)。

这是最终结果:

d <- lapply(1:nrow(a), function(i) {
  c[rep(i,3),]* outer(1:3, a[i,], "==") - c[rep(i,3),]
})

> d
[[1]]
     [,1] [,2] [,3] [,4] [,5]
[1,]  0.7  0.5 -0.3 -0.2  0.8
[2,] -0.1 -0.1  0.4 -0.2 -0.1
[3,] -0.1 -0.1 -0.3  0.6 -0.1

[[2]]
     [,1] [,2] [,3] [,4] [,5]
[1,] -0.3 -0.2 -0.1  0.5 -0.1
[2,]  0.3  0.5 -0.1 -0.2  0.5
[3,] -0.3 -0.2  0.7 -0.2 -0.1

[[3]]
     [,1] [,2] [,3] [,4] [,5]
[1,] -0.2 -0.3  0.6 -0.2  0.6
[2,] -0.2 -0.3 -0.1  0.4 -0.3
[3,]  0.6  0.6 -0.1 -0.2 -0.3