0

Assume the following data structure with a bunch of other data columns in the same tibble (not shown here) - the two columns in question are what's important.

data <- tibble(id = c(1,2,3,4,5,6,7,8,9), email = c(rep('aaa@aaa.com',3), rep('bbb@bbb.com', 3), rep('ccc@ccc.com', 3)))

I'm trying to 1) write individual xlsx files based on the email column (1 per email address) and 2) write the individual ids for an email into separate tabs in the xlsx.

This is what I have so far, but it's not fully implementing what I need.

for(i in unique(data$email)){
  
  print(data %>% filter(email == i))
  
  for(j in unique(data %>% filter(email == i) %>% select(id))){

    print(length(j))
    
    for(k in j){
      write.xlsx(data %>% filter(id == k), file = paste('./test_', k, '.xlsx'), sheetName = names(j)[k], append = TRUE)
    }
  }
      
  }
Dharman
  • 21,838
  • 18
  • 57
  • 107
Primesty
  • 89
  • 8
  • 1
    It can be done more easily `lst1 write.xlsx(lst1, 'file1.xlsx')` if you need a single file with different sheets. or different files, then `iwalk(lst1, ~ write.xlsx(.x, ~str_c('test_', .y)))` – akrun Jul 17 '20 at 19:30
  • Thanks for the answer @akrun! I tried doing `iwalk(lst_2, ~ write.xlsx(.x, ~str_c('./test_', .y, '.xlsx')))` but get this error: `Error in basename(file) : a character vector argument expected`. Any idea why? – Primesty Jul 20 '20 at 13:48
  • @akrun, never mind, I figured it out-ish. The problem was the `~` in front of the `str_c()` function. This works `iwalk(lst, ~ write.xlsx(.x, str_c('./test_', .y, '.xlsx')))`. The only problem I still have is that, while it is split by `email` now, the individual ids for a unique email address are still not written into individual sheets in the spreadsheet. So that'd be the piece de resistance :) – Primesty Jul 20 '20 at 15:19

1 Answers1

1
lst <- split(data, data$email)
writexl::write_xlsx(lst, "file.xlsx")
Jakub.Novotny
  • 2,089
  • 2
  • 4
  • 16