用向量(条件)对矩阵的值进行子集化

subsetting values of matrix with a vector (conditions)

我有以下矩阵:

>  matrix <- matrix(c(1,3,4,NA,NA,NA,3,0,4,6,0,NA,2,NA,NA,2,0,1,0,0), nrow=5,ncol=4)
> n <- matrix(c(1,2,5,6,2),nrow=5,ncol=1)

如您所见,对于每一行我都有

  1. 多个 NA - NA 的数量未定义
  2. 一个“0”

我想将 0 子集化为 n 的值。预期输出如下。

> output <- matrix(c(1, 3, 4,NA,NA,NA,3,5,4,6,1,NA,2,NA,NA,2,2,1,6,2), nrow=5,ncol=4)

我试过以下方法

subset <- matrix == 0 & !is.na(matrix)
matrix[subset] <- n
#does not give intended output, but subset locates the values i want to change

在我的 "real" 数据上使用时,我收到以下消息:

Warning message: In m[subset] <- n : number of items to replace is not a multiple of replacement length

谢谢

编辑:在矩阵中添加一行,因为我现实生活中的问题是矩阵不平衡。我在这里使用矩阵而不是 DF,因为我认为(不确定)对于非常大的数据集,R 对于大矩阵而不是数据帧的子集更快。

您似乎想按行替换值,但子集化是按列替换值(也许这不是一个完全详尽的解释)。转置矩阵将得到所需的输出:

matrix <- t(matrix)
subset <- matrix == 0 & !is.na(matrix)
matrix[subset] <- n
matrix <- t(matrix)

setequal(output, matrix)
[1] TRUE

您可以尝试使用此选项 ifelse:

ifelse(matrix == 0, c(n) * (matrix == 0), matrix)

#     [,1] [,2] [,3] [,4]
#[1,]    1   NA    1    2
#[2,]    3   NA   NA    2
#[3,]    4    3    5   NA
#[4,]   NA    6   NA    2

zero = matrix == 0
identical(ifelse(zero, c(n) * zero, matrix), output)
# [1] TRUE

我们可以使用

out1 <- matrix+n[row(matrix)]*(matrix==0)
identical(output, out1)
#[1] TRUE