r语言 - 下标出界时显示NA值



假设下面是矩阵

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

现在,我想获取两个名字的列,也就是

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

用这个我得到低错误:

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

是否有任何方法返回不可用列的NA值?

谢谢你的输入。

虽然这是一件非常奇怪的事情,但这里有一种方法可以做到:

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

最新更新