我正在尝试写一个代码来模拟大小为4*16*10的3D数组,其中每个单元包含10*10个矩阵
到目前为止,我已经嵌套了for循环,但是它们非常慢。我想用apply或mapply函数替换它们。
M=10
N=10
c=2
n=seq(1, 4, by=1)
p=0.25
q=seq(1,0.25, by =-0.05)
ntrials = 10
for (i in 1:length(n)){
for (j in 1:length(q)){
for (k in 1:ntrials){
plant_subm=matrix_plantsubm(M,N,c,n,p,q)
}
}
}这里,matrix_plantsubm是一个生成10*10矩阵的函数。我需要为n和q中的每一个选择获取矩阵,并重复此操作10次。
我是R的新手,不知道如何改进我的代码。任何帮助都是非常感谢的。
发布于 2019-06-05 12:51:16
数据(OP)
M=10
N=10
c=2
n=seq(1, 4, by=1)
p=0.25
q=seq(1,0.25, by =-0.05)
ntrials = 10创建参数,通过pmap传递给函数
这将创建所需的所有值组合
params <- expand.grid(
trial = 1:10,
M = M,
N = N,
c = c,
n = n,
p = p,
q = q
) %>%
as_tibble()
View(params)
# > nrow(params)
# [1] 640
# replace with your own, of course
my_madeup_function <-
function(M, N, c, n, p, q) {
matrix(data = rep(M * N + c - n * p * q, 100),
nrow = 10,
ncol = 10)
}
# we use `purrr::pmap`, an apply-type function to pass all of the parameters (except for trials) to the function:
result <- tibble(matrix = pmap(select(params, -trial), my_madeup_function))将参数和结果绑定到一个很好的摘要中:
summary <- bind_cols(params, result)让我们来看看结果:
> summary
# A tibble: 640 x 8
trial M N c n p q matrix
<int> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <list>
1 1 10 10 2 1 0.25 1 <dbl[,10] [10 x 10]>
2 2 10 10 2 1 0.25 1 <dbl[,10] [10 x 10]>
3 3 10 10 2 1 0.25 1 <dbl[,10] [10 x 10]>
4 4 10 10 2 1 0.25 1 <dbl[,10] [10 x 10]>
5 5 10 10 2 1 0.25 1 <dbl[,10] [10 x 10]>
6 6 10 10 2 1 0.25 1 <dbl[,10] [10 x 10]>
7 7 10 10 2 1 0.25 1 <dbl[,10] [10 x 10]>
8 8 10 10 2 1 0.25 1 <dbl[,10] [10 x 10]>
9 9 10 10 2 1 0.25 1 <dbl[,10] [10 x 10]>
10 10 10 10 2 1 0.25 1 <dbl[,10] [10 x 10]>
# ... with 630 more rows我们可以选择一个特定的类型,如下所示:
summary %>%
filter(trial == 8, n == 2, q == 0.5) %>%
.$matrix %>%
.[[1]]在我的机器上,microbenchmark::microbenchmark报告的运行时间大约是7ms,但这是我的“虚拟”函数。希望你的函数也能运行的很快。祝好运。
https://stackoverflow.com/questions/56449089
复制相似问题