简体   繁体   中英

How to create multiple dataframes with lapply()?

I want do same things to create different data frames, can I use lapply achieve?

I tried to did it but not succeed

xx<-c("a1","b1")
lapply(xx, function(x){
  x<-data.frame(c(1,2,3,4),"1")
})

I hope I can get two data frames ,like

a1<-data.frame(c(1,2,3,4),"1")
b1<-data.frame(c(1,2,3,4),"1")

You could try using sapply over the xx vector of names to populate a list with the data frames:

lst <- list()
xx <- c("a1", "b1")
sapply(xx, function(x) {
    lst[[x]] <- data.frame(c(1,2,3,4), "1")
})

Then, you may access each data frame using the list, eg lst$a1 .

An option that assigns to the .Globalenv . This as pointed out is less efficient but was provided to answer the OP's question as is:

lapply(xx, function(x) assign(x,data.frame(A=c(1,2,3,4),
                                       B="1"),
                           envir=.GlobalEnv))

You can then call each data frame with their names. a1 , b1 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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