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

时间:2017-03-07 14:23:40

标签: r extract subset extraction

我有以下矩阵:

>  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. 多个NAs - 数量NAs未定义
  2. 一个单一&#34; 0&#34;
  3. 我想将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
    

    用于我的&#34;真实&#34;数据我收到以下消息:

      

    警告消息:在m [子集]&lt; - n:要替换的项目数不是   替换长度的倍数

    由于

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

3 个答案:

答案 0 :(得分:1)

看起来你想要按行替换值,但是子集正在按列替换值(也许这不是一个完全彻底的解释)。转置矩阵将获得所需的输出:

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

setequal(output, matrix)
[1] TRUE

答案 1 :(得分:1)

您可以使用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

答案 2 :(得分:1)

我们可以使用

来做到这一点
out1 <- matrix+n[row(matrix)]*(matrix==0)
identical(output, out1)
#[1] TRUE
相关问题