简体   繁体   中英

Loop for extracting data.frame from list

I am trying to modify several dataframes with a loop of commands.

This is what I've tried:

F.list2 <- list(AUDTTO, BRLTTO, CADTTO, CHFTTO, EURTTO, GBPTTO, JPYTTO, MXNTTO, NZDTTO, RBLTTO, ZARTTO)
res3 <- lapply(
  F.list2, 
  function(x)
  {
    names(x)[names(x) == "Leveraged Funds Longs"] <- "Long"
    names(x)[names(x) == "Leveraged Funds Shorts"] <- "Short"
    select(x, "Date", "Long", "Short")
  }  
)

# ADD THIS PART TO THE LOOP?

AUDTTO <- res3[[1]]
BRLTTO <- res3[[2]]
CADTTO <- res3[[3]]
CHFTTO <- res3[[4]]
EURTTO <- res3[[5]]
GBPTTO <- res3[[6]]
JPYTTO <- res3[[7]]
MXNTTO <- res3[[8]]
NZDTTO <- res3[[9]]
RBLTTO <- res3[[10]]
ZARTTO <- res3[[11]]

As mentioned in the code, I'd like to add the last part to the loop.

Use a named list.

Without changing much of your code here is a way to get your expected output.

F.list2 <- tibble::lst(AUDTTO, BRLTTO, CADTTO, CHFTTO, EURTTO, GBPTTO, 
                       JPYTTO, MXNTTO, NZDTTO, RBLTTO, ZARTTO)

res3 <- lapply(F.list2, function(x){
           names(x)[names(x) == "Leveraged Funds Longs"] <- "Long"
           names(x)[names(x) == "Leveraged Funds Shorts"] <- "Short"
           dplyr::select(x, "Date", "Long", "Short")
         })

res3 now is a named list again. You can get individual dataframes using list2env .

list2env(res3, .GlobalEnv)

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