【问题标题】:show NA values when subscript out of bound下标越界时显示 NA 值
【发布时间】:2021-10-30 03:38:11
【问题描述】:

假设我有下面的矩阵

Mat = matrix(1:16, nrow = 4, ncol = 4, dimnames = list(as.character(1:4), as.character(16:19)))

现在假设,我想获取 2 个名称的列,即

Mat[, c('16', '1')]

这样我得到了低错误:

Error in Mat[, c("16", "1")] : subscript out of bounds

有没有办法为不可用的列返回NA 值?

感谢您的意见。

【问题讨论】:

  • 最好的方法是使用某种函数来尝试和索引,然后在其中放置一个try/catch。但我认为更大的问题是为什么你想这样做?
  • 类似于Mat[, which(c('16', '1') %in% colnames(Mat) == TRUE)] 的东西。否则有点令人费解的tryCatch,但不知道您的用例是什么。确实,为什么?
  • 我需要这样做的原因基本上是基于广泛的外部向量(此处为x)对我的矩阵进行基准测试。我有不同的行和列的不同矩阵,我需要用相同的列和行使它们看起来相似。希望这可以澄清。

标签: r matrix


【解决方案1】:

虽然这是一件很奇怪的事情,但您可以这样做:

Mat <- matrix(1:16, nrow = 4, ncol = 4, dimnames = list(as.character(1:4), as.character(16:19)))

getColumns <- function(Mat, indicies) {
    mat_cols <- colnames(Mat)
    missing <- indicies[!(indicies %in% mat_cols)]
    present <- indicies[(indicies %in% mat_cols)]
    result <- cbind(
        Mat[, present],
        matrix(NA, nrow = nrow(Mat), ncol = length(missing))
    )
    colnames(result) <- c(present, missing)
    return(result)
}

> getColumns(Mat, c("1", "2", "17", "19"))
  17 19  1  2
1  5 13 NA NA
2  6 14 NA NA
3  7 15 NA NA
4  8 16 NA NA

【讨论】:

  • 可以做到,对于丢失的行也可以做类似的事情,但仍然希望听到为什么这会有用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-21
相关资源
最近更新 更多