简体   繁体   English

如何从矩阵中删除任何内容?

[英]How to remove nothing from a matrix?

From a matrix M ,从矩阵M

> (M <- matrix(1:9, 3, 3))
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9

I want to remove/keep columns by condition and put the result into a list.我想按条件删除/保留列并将结果放入列表中。 There's no problem as long as the condition consists of integers without c(NA, 0) , eg只要条件由没有c(NA, 0)的整数组成就没有问题,例如

cv1 <- 1:3
lapply(cv1, function(x) M[, -x])

For the case there's no column to remove I tried to add NA or 0 to the condition vector, but it won't work.对于没有要删除的列的情况,我尝试将NA0添加到条件向量中,但它不起作用。

cv2 <- c(NA, 1:3)
cv3 <- 0:3

> lapply(cv2, function(x) M[, -x])[[1]]
[1] NA NA NA

> lapply(cv3, function(x) M[, -x])[[1]]

[1,]
[2,]
[3,]

I know I can do我知道我能做到

lapply(cv2, function(x) {
  if (is.na(x))
    M
  else
    M[, -x]
})

but I wonder if there's a simpler way.但我想知道是否有更简单的方法。

Actually question:其实问题:

What strikes me in the first place is that the matrix disappears instead of remaining complete in following cases, although I'm actually trying to remove nothing:首先让我印象深刻的是,矩阵在以下情况下消失而不是保持完整,尽管我实际上试图删除任何内容:

M[, -(na.omit(NA))]
M[, na.omit(-(NA))]
M[, -0]
M[, -logical(0)]

# [1,]
# [2,]
# [3,]

or或者

> M[, -NULL]
Error in -NULL : invalid argument to unary operator

Can somebody explain the reason and the advantage of this behavior, and/or how to say it right?有人可以解释这种行为的原因和优势,和/或如何正确表达?

The reason is pretty simple: the minus sign in -x isn't treated as something special, it's just a regular mathematical operation.原因很简单: -x的减号不被视为特殊的东西,它只是一个常规的数学运算。 So -0 is the same as 0 , and -NA is the same as NA .所以-00相同, -NANA相同。

@Cettt gave one answer: setdiff(seq_len(ncol(M)), x) will give the column numbers other than x . @Cettt 给出了一个答案: setdiff(seq_len(ncol(M)), x)将给出x以外的列号。 You can do the same sort of thing using logical indexing as seq_len(ncol(M)) != x will work if x is a number, but not if x is NA .你可以使用逻辑索引做同样的事情,因为seq_len(ncol(M)) != x如果x是一个数字就会工作,但如果xNA不行。 If you really need to handle that case too, you could use is.na(x) | seq_len(ncol(M)) != x如果你真的需要处理这种情况,你可以使用is.na(x) | seq_len(ncol(M)) != x is.na(x) | seq_len(ncol(M)) != x , but @Cettt's solution looks simpler. is.na(x) | seq_len(ncol(M)) != x ,但@Cettt 的解决方案看起来更简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM