O.HENRY
O.HENRY

Reputation: 27

Make List easier with For-Loop

library(xml2)
library(rvest)

datpackage <- paste0("dat",1:10)

for(i in 1:10){

  assign(datpackage[i], runif(2))

}

datlist <- list(dat1, dat2, dat3, dat4, dat5, dat6, dat7, dat8, dat9, dat10)

"datlist" is what I want, but is there easier way to make a list ?

datlist2 <- for (i in 1:10) {
                list(paste0("dat",i))
}

datlist3 <- list(datpackage)
I've tried datlist2, and datlist3, but that's not the same as "datlist".

What should I have to do when I make a list with thousands of data?

Upvotes: 2

Views: 55

Answers (2)

Konrad
Konrad

Reputation: 18585

For creating lists with random numbers I would also suggest:

datlist2 <- lapply(vector("list", 10), function(x) {runif(2)})

Benchmarking

May be worth adding that the lapply / vector approach appears to be faster:

funA <- function(x) {replicate(10, runif(2), simplify = FALSE)}
funB <- function(x) {lapply(vector("list", 10), function(x) {runif(2)})}
microbenchmark::microbenchmark(funA(), funB(), times = 1e4)

Results

Unit: microseconds
   expr    min      lq     mean  median      uq      max neval cld
 funA() 24.053 27.3305 37.98530 28.6665 34.4045 2478.510 10000   b
 funB() 19.507 21.6400 30.37437 22.9235 27.0500 2547.145 10000  a 

Comparison - funA / funB

Upvotes: 2

akrun
akrun

Reputation: 886938

We can use paste with mget if the objects are already created

datlist <- mget(paste0("dat", 1:10))

But, if we need to create a list of random uniform numbers,

datlist <- replicate(10, runif(2), simplify = FALSE)

Upvotes: 3

Related Questions