我是 R 新手。我创建了一个对象 a:
a <- c(2,4,6,8,10,12,14,16,18,20)
我对向量执行了以下操作:
a[!c(10,0,8,6,0)]
我得到的输出为 4 10 14 20
我确实明白 !c(10,0,8,6,0)
产生的输出为 FALSE TRUE FALSE FALSE TRUE
我不明白最后的结果是怎么出来的 4 10 14 20
有人可以帮忙吗?
最佳答案
我们获得结果是因为逻辑向量被回收(因为它的长度仅为 5,而 length(a)
的长度为 10)以满足 'a' 向量 i 的结尾。
i1 <- rep(!c(10,0,8,6,0), length.out = length(a))
i1
[1] FALSE TRUE FALSE FALSE TRUE FALSE TRUE FALSE FALSE TRUE
如果我们使用该向量
a[i1]
[1] 4 10 14 20
如果我们只传递TRUE
,则更容易理解,然后TRUE将被回收以返回所有元素,或者与FALSE
相反
a[TRUE]
[1] 2 4 6 8 10 12 14 16 18 20
a[FALSE]
numeric(0)
?Extract
的文档中提到了回收
For [-indexing only: i, j, ... can be logical vectors, indicating elements/slices to select. Such vectors are recycled if necessary to match the corresponding extent. i, j, ... can also be negative integers, indicating elements/slices to leave out of the selection.
在大多数语言中,0 被视为 FALSE,其他值被视为 TRUE。因此,当我们否定 0 (FALSE) 时,将转换为 TRUE,将所有其他值转换为 FALSE
关于r - 使用逻辑向量进行向量索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68512905/