Stataq
Stataq

Reputation: 2301

how to loop two loops one in another

I have a list (lst1) which contain 10 data.frame. Each data.frame has a variable ID. I also have a IDlist. Is it a way that we can create a looping codes so I can generate an excel book which contain those 10 data, one in each sheet, with one match ID in IDlist?

The tricky part is we need to looping through the IDlist list as well as passing through the lst1. Any advice?

I have some codes that I wrote but it won't work. Hopefully it can give you some idea on what I want to do.

for (i in IDlist) {
  
  # create a workbook
  tempwb <- createWorkbook()
  
  for(j in seq_along(lst1)){

    # store the ID -specific subset of the dataset
     data.subset <-lst1[[j]] %>% filter(ID == i)

    # add worksheet
    addWorksheet(tempwb, sheetName = lst1[[j]])} # I want the sheetname= dataname, what should I do? mine should be wrong

## How can I load subset to each sheet?

    file.name <- paste0(i,".xlsx")

    ### save workbook
    saveWorkbook(tempwb, paste0(output_dir,file.name), overwrite = TRUE)
  }

Upvotes: 0

Views: 58

Answers (2)

Michael Dewar
Michael Dewar

Reputation: 3248

library(tidyverse)
library(writexl)

lst1 <- list(data1 = mpg, data2 = mpg, data3 = mpg, `data4/\\bad name` = mpg)

# Remove any illegal characters from names:
names(lst1) <- names(lst1) %>% 
    stringr::str_replace_all("[:punct:]", " ")

IDlist <- mpg %>% pull(cyl) %>% unique

make_one_xlsx <- function(this_id){
    lst1 %>% map(~filter(., cyl == this_id)) %>% write_xlsx(paste0("ID_", this_id, ".xlsx"))
}

IDlist %>% map(make_one_xlsx)

Upvotes: 1

sammy
sammy

Reputation: 437

you should show some example of your data for better answers.

you could use xlsx library

library('xlsx')


for(i in seq_along(lst1)){
    if(i == 1){
        append = FALSE
    } else{
        append = TRUE
    }
    write.xlsx(lst1[i], file='file_name.xlsx', 
               sheetName='get your id(sheet) name', append=append)
}

Upvotes: 1

Related Questions