1

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:

[[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. I tried with for loop in this way:

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

R tell me:

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

How can do it with for loop or lapply function?

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.