简体   繁体   English

如何使用此值填充数组(for 循环或 lapply 函数)?

[英]How fill an array with this values (for loop or lapply function)?

I have this values (simplify example):我有这个值(简化示例):

a  #class numeric
 [1] 1 5 7 6 9

and this array:和这个数组:

res.tot <- array(NA,dim=c(2,1,5))

I need to fill the array res.tot with a values, in this way:我需要用a值填充数组res.tot ,以这种方式:

[[1]]
     [1]
[1] 1
[2] 1

[[2]]
     [1]
[1] 5
[2] 5

...
[[5]]
     [1]
[1] 9
[2] 9

in the array res.tot each value of a is repeated 2 times, and each repeated a value occupay a different z dimension.在数组res.tota每个值都重复了 2 次,每个重复a值占据了不同的 z 维度。 I tried with for loop in this way:我以这种方式尝试使用for循环:

for (i in 1:length(a)){
  res.1 <- data.frame(rep(a[i],2))
  res.tot[,,i] <- res.1
  }

R tell me: R告诉我:

Error in res.tot.1[, , i] <- res.1 : incorrect number of subscripts

How can do it with for loop or lapply function?如何使用for looplapply函数做到这lapply

Here is a brute force solution:这是一个蛮力解决方案:

> a <- c(1,5,7,6,9)
> res.tot <- array(NA,dim=c(2,1,5))
> for (i in 1:(dim(res.tot)[1])) {
+   for (j in 1:(dim(res.tot)[2])) {
+     for (k in 1:(dim(res.tot)[3])) {
+       res.tot[i,j,k] <- a[k]
+     }
+   }
+ }
> res.tot
, , 1

     [,1]
[1,]    1
[2,]    1

, , 2

     [,1]
[1,]    5
[2,]    5

, , 3

     [,1]
[1,]    7
[2,]    7

, , 4

     [,1]
[1,]    6
[2,]    6

, , 5

     [,1]
[1,]    9
[2,]    9

and here is a one-liner solution:这是一个单线解决方案:

> res.tot[] <- rep(a,each=2)
> res.tot
, , 1

     [,1]
[1,]    1
[2,]    1

, , 2

     [,1]
[1,]    5
[2,]    5

, , 3

     [,1]
[1,]    7
[2,]    7

, , 4

     [,1]
[1,]    6
[2,]    6

, , 5

     [,1]
[1,]    9
[2,]    9

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM