如何循环遍历数据矩阵并计算 select 行?

How can I loop through a data matrix and compute on select rows?

我有以下名为 matrix1 的数据矩阵:

  [,1] [,2] [,3] [,4] [,5] [,6]
A    1    1    4    1   19   15
C    2    1    1    1    1    1
G    1   19   15   19    1    4
T   18    1    2    1    1    2

对于 A 行和 T 行,我想将所有值除以 0.3。对于 C 和 G 行,我希望将所有值除以 0.2。然后我希望在名为 matrix2 的矩阵中返回新值。

有没有办法循环遍历此矩阵或使用条件语句将正确的行除以正确的值?请告诉我!!

set.seed(1)
matrix1 <- matrix(rpois(24, lambda = 5), 4, 6)
rownames(matrix1) <- c("A", "C", "G", "T")
matrix1

#  [,1] [,2] [,3] [,4] [,5] [,6]
#A    4    3    6    6    6    9
#C    4    8    2    4   11    3
#G    5    9    3    7    4    6
#T    8    6    3    5    7    3


matrix2 <- matrix1 # make copy
ATs <- which(rownames(matrix1) %in% c("A", "T")) # index of A&T
CGs <- which(rownames(matrix1) %in% c("C", "G")) # index of C&G
matrix2[ATs,] <- matrix1[ATs,] / 0.3
matrix2[CGs,] <- matrix1[CGs,] / 0.2
matrix2

#      [,1] [,2] [,3]     [,4]     [,5] [,6]
#A 13.33333   10   20 20.00000 20.00000   30
#C 20.00000   40   10 20.00000 55.00000   15
#G 25.00000   45   15 35.00000 20.00000   30
#T 26.66667   20   10 16.66667 23.33333   10

或者,作为一个循环:

for(i in seq(nrow(matrix1))){
  if(rownames(matrix1)[i] %in% c("A", "T")){
    matrix2[i,] <- matrix1[i,] / 0.3
  } else {
    matrix2[i,] <- matrix1[i,] / 0.2
  }
}

试试下面的代码

matrix1 / ifelse(rownames(matrix1) %in% c("A", "T"), 0.3, 0.2)

这给出了

       [,1]      [,2]      [,3]      [,4]      [,5]      [,6]
A  3.333333  3.333333 13.333333  3.333333 63.333333 50.000000
C 10.000000  5.000000  5.000000  5.000000  5.000000  5.000000
G  5.000000 95.000000 75.000000 95.000000  5.000000 20.000000
T 60.000000  3.333333  6.666667  3.333333  3.333333  6.666667

数据

> dput(matrix1)
structure(c(1L, 2L, 1L, 18L, 1L, 1L, 19L, 1L, 4L, 1L, 15L, 2L,
1L, 1L, 19L, 1L, 19L, 1L, 1L, 1L, 15L, 1L, 4L, 2L), .Dim = c(4L,
6L), .Dimnames = list(c("A", "C", "G", "T"), NULL))

我们也可以

matrix1/c(0.2, 0.3)[1+(rownames(matrix1) %in% c("A", "T"))] 

-输出

  [,1]      [,2]      [,3]      [,4]      [,5]      [,6]
A  3.333333  3.333333 13.333333  3.333333 63.333333 50.000000
C 10.000000  5.000000  5.000000  5.000000  5.000000  5.000000
G  5.000000 95.000000 75.000000 95.000000  5.000000 20.000000
T 60.000000  3.333333  6.666667  3.333333  3.333333  6.666667

数据

matrix1 <- structure(c(1L, 2L, 1L, 18L, 1L, 1L, 19L, 1L, 4L, 1L, 15L, 2L,
1L, 1L, 19L, 1L, 19L, 1L, 1L, 1L, 15L, 1L, 4L, 2L), .Dim = c(4L,
6L), .Dimnames = list(c("A", "C", "G", "T"), NULL))