r - 奇怪的括号赋值调用 ('[<-' ) 和矩阵参数

标签 r list matrix assignment-operator

最近我偶然发现了这段代码:

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/

相关文章:

r - 具有用户身份验证的 Shiny 仪表板

r - 将两个维恩图放在一张图表上

python - 从字符串列表的元素中删除尾随换行符

java - 执行过滤: List<>

r - 在 R 中将数字矩阵转换为颜色矩阵

r - 在 R 中的每行文本之间插入带有递增编号的新行

php - 如何从 php 文件中获取已声明函数及其数据的列表?

perl - 如何计算两个数组中每个元素之间的差异?

c++ - OpenCV - 直接将矩阵乘法结果复制到另一个矩阵的子集

在 R 中重新排列数据框