问题
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)
In reality, my 3D array contains 366 rows, 8 columns and 10000 observations for the 3rd dimension. How can I automate this?
回答1:
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(...) 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.
来源:https://stackoverflow.com/questions/51297035/efficient-way-to-fill-a-3d-array