填充 3D 数组的有效方法 [英] Efficient way to fill a 3D array

查看:49
本文介绍了填充 3D 数组的有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试寻找一种有效的方法来填充 3D 数组.特别是,我想用前一列的值填充数组的列.

I’m trying to find an efficient way to fill a 3D array. In particular, I want to fill the array's columns with the values of the previous columns.

这是一个可重现的示例.

Here is a reproducible example.

set.seed(1234)
no_ind <- 10
time_period <- 8

## Define the 3D array
col_array <- c(paste("day_", seq(0, 7, 1), sep=""))
test <- array(0, dim=c(time_period, length(col_array), no_ind), dimnames=list(NULL, col_array, as.character(seq(1, no_ind, 1))))
print(test)

## Initialize the array
test[1,c("day_0"),] <- round(runif(no_ind, 0, 100))
print(test)

## Fill the array
for(time in 1:(time_period - 1)){
for(ind in 1:no_ind){
  ## print(time)
  ## print(ind)
    test[time + 1,c("day_0"),ind] <- round(runif(1, 0, 100))
    test[time + 1,c("day_1"),ind] <- test[time,c("day_0"),ind]
    test[time + 1,c("day_2"),ind] <- test[time,c("day_1"),ind]
    test[time + 1,c("day_3"),ind] <- test[time,c("day_2"),ind]
    test[time + 1,c("day_4"),ind] <- test[time,c("day_3"),ind]
    test[time + 1,c("day_5"),ind] <- test[time,c("day_4"),ind]
    test[time + 1,c("day_6"),ind] <- test[time,c("day_5"),ind]
    test[time + 1,c("day_7"),ind] <- test[time,c("day_6"),ind]
  }
}

print(test)

实际上,我的 3D 数组包含 366 行、8 列和第 3 维的 10000 个观察值.如何自动执行此操作?

In reality, my 3D array contains 366 rows, 8 columns and 10000 observations for the 3rd dimension. How can I automate this?

推荐答案

您可以使用 sapply 的隐式(默认)simplify = TRUE 参数并生成使用 replicate

You could make use of sapplys implicit (by default) simplify = TRUE parameter and generate the 3D array in one step using replicate

dims <- c(8, 8, 10)   # The dimensions of your array
set.seed(2017)
arr <- replicate(dims[3], {
    rand <- round(runif(dims[1], 0, 100));
    sapply(seq_along(1:dims[1]), function(i)
        c(rep(0, i - 1), rand[1:(dims[1] - i + 1)])) })

sapply(...) 默认情况下具有 simplify = TRUE,并根据您的规范返回一个数组,其值位于下三角部分.replicate 然后将重复该过程 10 次.这也减少了 runif 调用的次数,因为我们绘制了 108 次随机数,而不是 10x8=80 单独随机数.

sapply(...) has simplify = TRUE by default, and returns an array with values in the lower triangular part according to your specifications. replicate will then repeat the process 10 times. This also reduces the number of runif calls, as we draw 10 times 8 random numbers, rather than 10x8=80 random numbers individually.

这篇关于填充 3D 数组的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆