最近我偶然发现了这段代码:
y <- NULL
y[cbind(1:2, 1:2)] <- list( list(1,2), list(2,3))
来自第二个答案here .
但是看起来和y <- list(...)
没有什么区别,如下比较所示:
> identical(y, list( list(1,2), list(2,3)))
[1] TRUE
> identical(y, y[cbind(1:2, 1:2)])
[1] FALSE
这里的括号赋值是怎么回事?为什么它不抛出错误?还有为什么最后一行代码和非赋值版本不一样呢?
最佳答案
矩阵索引仅在 y
时适用已暗淡。将此与标准 R
结合起来回收以及所有矩阵实际上都是向量的事实,这种行为是有道理的。
当你初始化y
时设置为 NULL,确保它没有暗淡。因此,当您索引y
时通过矩阵,例如 ind
,您会得到与调用 y[as.vector(ind)]
相同的结果
identical(y[ind], y[as.vector(ind)])
# [1] TRUE
如果ind
中有重复值并且您还分配了,那么对于每个索引,仅保留为其分配的最后一个值。例如,假设我们正在执行
y <- NULL; y[cbind(1:2, 2:1)] <- list( list(1,2), list(3,4) )
# y has no dimension, so `y[cbind(1:2, 2:1)]`
# is the equivalent of `y[c(1:2, 2:1)]`
当您分配 y[c(1, 2, 2, 1)] <- list("A", "B")
时,实际上发生的情况类似于:
y[[1]] <- "A"
y[[2]] <- "B"
y[[2]] <- "B" # <~~ 'Overwriting' previous value
y[[1]] <- "A" # <~~ 'Overwriting' previous value
下面是对所发生的索引的进一步查看:(注意前两个字母是如何重复的)
ind <- cbind(1:2, 1:2)
L <- as.list(LETTERS)
L[ind]
# [[1]]
# [1] "A"
#
# [[2]]
# [1] "B"
#
# [[3]]
# [1] "A"
#
# [[4]]
# [1] "B"
这是同样的事情,现在有分配。 请注意如何仅保留分配的第三个和第四个值。
L[ind] <- c("FirstWord", "SecondWord", "ThirdWord", "FourthWord")
L[ind]
# [[1]]
# [1] "ThirdWord"
#
# [[2]]
# [1] "FourthWord"
#
# [[3]]
# [1] "ThirdWord"
#
# [[4]]
# [1] "FourthWord"
尝试不同的索引以获得更清晰的结果:
ind <- cbind(c(3, 2), c(1, 3)) ## will be treated as c(3, 2, 1, 3)
L <- as.list(LETTERS)
L[ind] <- c("FirstWord", "SecondWord", "ThirdWord", "FourthWord")
L[1:5]
# [[1]]
# [1] "ThirdWord"
#
# [[2]]
# [1] "SecondWord"
#
# [[3]]
# [1] "FourthWord"
#
# [[4]]
# [1] "D"
#
# [[5]]
# [1] "E"
L[ind]
# [[1]]
# [1] "FourthWord"
#
# [[2]]
# [1] "SecondWord"
#
# [[3]]
# [1] "ThirdWord"
#
# [[4]]
# [1] "FourthWord"
编辑@agstudy的问题:
查看 src 中的 [
我们有以下评论:
- The special [ subscripting where dim(x) == ncol(subscript matrix)
- is handled inside VectorSubset. The subscript matrix is turned
- into a subscript vector of the appropriate size and then
- VectorSubset continues.
查看函数static SEXP VectorSubset(SEXP x, SEXP s, SEXP call)
相关检查如下:
/* lines omitted */
attrib = getAttrib(x, R_DimSymbol);
/* lines omitted */
if (isMatrix(s) && isArray(x) && ncols(s) == length(attrib)) {
/* lines omitted */
...
关于r - 奇怪的括号赋值调用 ('[<-' ) 和矩阵参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18044004/