HaagenDaz
HaagenDaz

Reputation: 461

how to get data frames within lists?

I am using the following code to run simulations. How can I get a from x1? I have tried lapply below but doesn't seem to work.

library(parallel)
clusterEvalQ(cl,library(evir))
set.seed(0)
system.time(
 x1 <- parLapply(cl, 1:100000,
   function(i) {
       n1 <- rpois(1,4)
       n2<-  rpois(1,7)
       list(data.frame(a=rexp(n1, rate=0.1),a1=rexp(n1, rate=0.6)), 
            data.frame(b=rexp(n2, rate=0.7),b1=rexp(n2, rate=0.6)))

   }
  )
)

y1<-lapply(x1, '[', , "a")

Upvotes: 0

Views: 51

Answers (1)

Julius Vainora
Julius Vainora

Reputation: 48211

y1 <- lapply(x1, function(x) x[[1]][["a"]])

gives a required list of vector assuming that the number of a data frame is known and equals 1. More generally:

y1 <- Filter(Negate(is.null), sapply(unlist(x1, rec = FALSE), `[[`, "a"))

Upvotes: 1

Related Questions