我有以下矩阵:
> 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)
您可以看到,对于我有的每行
- 多个NAS- NUMBEN NAS不确定
- 一个单曲" 0"
我想为n的值子集0。
的预期输出。> 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
在我的"真实"数据上使用时,我会收到以下消息:
警告消息:在m [subset]&lt; - n中:要替换的项目数不是 替换长度的倍数
谢谢
编辑:在矩阵中添加了一行,因为我的现实生活中的问题与矩阵不平衡。我在这里使用矩阵而不是DF,因为我认为(不确定)使用非常大的数据集,R更快地使用大型矩阵而不是数据框架子集。
我们可以使用
做到这一点out1 <- matrix+n[row(matrix)]*(matrix==0)
identical(output, out1)
#[1] TRUE
看来您想通过行替换值,但是子集是通过列替换值(也许这不是一个完全彻底的解释)。矩阵矩阵将获得所需的输出:
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