【问题标题】:Dynamically indexing of multidimensional arrays [duplicate]多维数组的动态索引[重复]
【发布时间】:2021-05-28 05:18:45
【问题描述】:

假设我们有一个像这样的 3 维数组

a <- array(1:24, dim = c(4, 3, 2))

访问或索引数组通常通过

# fixing the third (=last) dimension and output the corresponding values of the first and second dimension
a[, , 1] 

> a
, , 1

     [,1] [,2] [,3]
[1,]    1    5    9
[2,]    2    6   10
[3,]    3    7   11
[4,]    4    8   12

在这个例子中,我知道维数是 3。因此,我可以手动输入两个逗号,后跟最后一个维度的数字(此处为 1)。但是现在我想通过先验地固定最后一个维度而不知道维度的数量来创建一个用于动态索引数组的表达式。此构造稍后应在循环中使用,例如lapply().

dims <- paste0(paste0(rep("", length(dim(a)) - 1L), collapse = ","), ",idx")

> dims
[1] ",,idx"

我是否能够将这个动态创建的字符串 ",,idx" 转换为任何内容 - 我知道索引本身并不是一个可用于索引的表达式?

a[dims] <- ... # won't work!

提前致谢!

【问题讨论】:

  • 你到底想要这个做什么?你想完成什么?
  • @Onyambu 我想编写一个函数,该函数能够将一个数组插入到另一个数组中关于最后一个维度的某个位置。这是一种 abind() 但选择插入数组应出现的位置。
  • 试试do.call('[', c(list(a), rep(list(TRUE), length(dim(a))-1), 1))
  • @all 感谢您的快速回复!

标签: r multidimensional-array


【解决方案1】:

这是一种方式,但我不确定它是否是您想要的方式:

write.table(paste0("a[",dims,"]"),"code.R",row.names = FALSE,col.names = FALSE,quote=FALSE)
source("code.R")$value

这将创建一个单独的 R 脚本,其中仅包含 a[,,idx],然后运行该脚本以返回值。

【讨论】:

  • 感谢您的回答。来自@Onyambu 和 user20650 的上述提示/解决方案效果很好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-05-25
  • 2021-02-05
  • 1970-01-01
  • 2021-11-10
  • 2016-03-20
  • 2011-11-17
  • 1970-01-01
相关资源
最近更新 更多