【问题标题】:subsetting values of matrix with a vector (conditions)用向量(条件)对矩阵的值进行子集化
【发布时间】:2017-03-07 14:23:39
【问题描述】:

我有以下矩阵:

>  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

在我的“真实”数据上使用时,我收到以下消息:

警告消息:在 m[子集]

谢谢

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

【问题讨论】:

    标签: r extract subset extraction


    【解决方案1】:

    我们可以使用

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

    【讨论】:

    • 谢谢,这适用于我的“缩放”示例。正在寻找这个
    【解决方案2】:

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

    matrix <- t(matrix)
    subset <- matrix == 0 & !is.na(matrix)
    matrix[subset] <- n
    matrix <- t(matrix)
    
    setequal(output, matrix)
    [1] TRUE
    

    【讨论】:

    • 感谢您,它确实适用于我提供的示例。我编辑了我的问题,因为我的现实生活数据不是平衡矩阵。为您的回复喝彩
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 2021-03-26
      • 1970-01-01
      • 2015-01-17
      • 2018-08-07
      • 2014-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多