我有一个多维数组,并尝试将值分配给特定的维度。请参阅下面的代码,了解我当前的方法。
# Create a array and fill with NA
set.seed(1)
dim_arr <- seq(2, 10)
arr <- array(NA, dim = dim_arr)
# Add values to the dimension 2 and fill other dimensions
add_dim <- 2
# Generate value
values <- runif(prod(dim_arr[-add_dim]))
# Assign value to position 1 of dimension 2
arr[,1,,,,,,,] <- values
values <- runif(prod(dim_arr[-add_dim]))
# Assign value to position 2 of dimension 2
arr[,2,,,,,,,] <- values
我的问题是维数(dim_arr)和更改的维数(add_dim)不固定。当参数dim_arr和add_dim更改时,代码“ arr [,1 ,,,,,,,]”被破坏了,我每次都必须对其进行更改。
有什么通用的方法可以改善我的代码吗?
如果我的问题不清楚,请告诉我。感谢您的任何建议。
正确的方法是调用do.call
指定除所需尺寸(例如do.call("[<-", list(arr, 1:x, 1:y, 3, values)
)以外的每个尺寸的完整范围。一种有趣的方法是利用神秘的丢失对象在中生成空参数x[,,,z,,,]
。
编辑:最后包含一个更无聊但更简单的方法,因为它证明了单个TRUE,因为参数等同于缺少的参数。
EDIT2:使用Hadley的substitute()
方法进行了简化。
replace_dim <- function(arr, rep.val, dim.to.rep, dim.val) {
dim.list <- replicate(length(dim(arr)), substitute())
dim.list[dim.to.rep] <- dim.val
do.call(`[<-`, c(list(arr), dim.list, list(rep.val)))
}
arr <- array(1:8, dim=rep(2, 3))
replace_dim(arr, 555, 3, 1) # note this doesn't modify `arr`, so you would have to set `arr` to the return value
# , , 1
# [,1] [,2]
# [1,] 555 555
# [2,] 555 555
# , , 2
# [,1] [,2]
# [1,] 5 7
# [2,] 6 8
replace_dim(arr, 555, 2, 1)
# , , 1
# [,1] [,2]
# [1,] 555 3
# [2,] 555 4
# , , 2
# [,1] [,2]
# [1,] 555 7
# [2,] 555 8
replace_dim(arr, 555, 1, 1)
# , , 1
# [,1] [,2]
# [1,] 555 555
# [2,] 2 4
# , , 2
# [,1] [,2]
# [1,] 555 555
# [2,] 6 8
replace_dim(arr, 555, 1, 2)
# , , 1
# [,1] [,2]
# [1,] 1 3
# [2,] 555 555
# , , 2
# [,1] [,2]
# [1,] 5 7
# [2,] 555 555
另外,在这里我们使用555
,但是您可以使用任何适合插入尺寸的矢量/对象。
replace_dim_boring <- function(arr, rep.val, dim.to.rep, dim.val) {
dim.list <- as.list(rep(T, length(dim(arr))))
dim.list[dim.to.rep] <- dim.val
do.call(`[<-`, c(list(arr), dim.list, list(rep.val)))
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句