Use lapply inside loop for?

Asked

Viewed 39 times

2

I would like to generate nBS reamostras for each of the N column vectors of size n of my matrix, and then return something like a list.

I got something similar to the one desired with the following (testing with equal values in the vector to make sure that the reamostras are from the respective columns):

v1 = c(1,3,2,4,1)
v2 = c(2,2,2,2,2)
dados = matrix(c(v1,v2),ncol = 2)
N = ncol(dados)
n = nrow(dados)
nBS <- 5

for (i in 1:N){
    y = dados[,i]
    lst <- lapply(1:N, function(x) matrix(sample(y,n,T), nrow = n, ncol = nBS))
}

But my exit apparently indicates that only the v2 was used in this resampling:

>  lst 
[[1]]
      [,1] [,2] [,3] [,4] [,5]
[1,]    2    2    2    2    2
[2,]    2    2    2    2    2
[3,]    2    2    2    2    2
[4,]    2    2    2    2    2
[5,]    2    2    2    2    2

[[2]]
      [,1] [,2] [,3] [,4] [,5]
[1,]    2    2    2    2    2
[2,]    2    2    2    2    2
[3,]    2    2    2    2    2
[4,]    2    2    2    2    2
[5,]    2    2    2    2    2

How do I scroll through all columns of my matrix and return nBS reamoysters in size n for each of my N vectors?

Thanks in advance for the help!

1 answer

3


You can do it many ways, here are three of them.

In both the whole work is done by

apply(dados, 2, sample, n, TRUE)

The difference is in how to call this instruction.

1st

Combine replicate with apply. The result is a "array" with 3 dimensions. A third dimension is nBS, the first two are the dimensions of the original matrix.

set.seed(1234)
res1 <- replicate(nBS, apply(dados, 2, sample, n, TRUE))

2nd

Combine lapply with apply.

set.seed(1234)
res2 <- lapply(seq_len(nBS), function(i) apply(dados, 2, sample, n, TRUE))

This time the result is a list, a class object "list". To compare the results I will use identical cyclically.

for(i in seq_len(nBS)) 
  print(identical(res1[,, i], res2[[i]]))

#[1] TRUE
#[1] TRUE
#[1] TRUE
#[1] TRUE
#[1] TRUE

3rd

This time with a cycle for. The results will be assigned to the members of a list previously created.

set.seed(1234)
res3 <- vector("list", length = nBS)
for(i in seq_len(nBS)){
  res3[[i]] <- apply(dados, 2, sample, n, TRUE)
}

As much as res2 as res3 are lists, we can compare directly.

identical(res2, res3)
#[1] TRUE
  • Thank you so much! Working beautifully the way I need! Clear and complete answer!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.