Jaskeil
Jaskeil

Reputation: 1232

Iterating over large dataframe to write individual Excel spreadsheets

I want to write unique spreadsheets based on the MVNDR number you see below

Current Data Strucutre/Data Frame

 Quote Date  eSVS Order Nbr  MVNDR     Name 
    2021-05-24  H6328-206574    60710435  Joe
    2021-05-27  H8926-157085    60710435  Joe 
    2021-05-24  H6328-206574    60710435  Carl
    2021-05-27  H8926-157085    60710435  Carl
    2021-05-24  H6328-206574    60710435 John
    2021-05-27  H8926-157085    60710435 John

Desired Output in a Unique Spreadsheet

Spreadsheet1 & Desired Path Name: C:\Users\santi\Documents\R_Scripts\MVNDR_Joe

Quote Date  eSVS Order Nbr  MVNDR     Name 
2021-05-24  H6328-206574    60710435  Joe
2021-05-27  H8926-157085    60710435  Joe 

Spreadsheet2 & Desired Path Name: C:\Users\santi\Documents\R_Scripts\MVNDR_John

Quote Date  eSVS Order Nbr  MVNDR    Name 
2021-05-24  H6328-206574    60710435 John
2021-05-27  H8926-157085    60710435 John

Spreadsheet3 & Desired Path Name: C:\Users\santi\Documents\R_Scripts\MVNDR_Carl

Quote Date  eSVS Order Nbr  MVNDR    Name 
2021-05-24  H6328-206574    60710435  Carl
2021-05-27  H8926-157085    60710435  Carl

Upvotes: 1

Views: 78

Answers (1)

norie
norie

Reputation: 9867

I've found what the problem is, and I should have spotted it earlier.

Since there's now more than one record for each group x$Name returns a vector with the name repeated for each record.

We only need the name and we can easily extract that.

Here's the updated code.

library(dplyr)
library(xlsx)

dat <- read.csv('data.csv')

dat_grouped <- dat %>% group_by(Name)

lapply(group_split(dat_grouped), function(x){write.xlsx(x, paste0(x$Name[1], ".xlsx"))})

Upvotes: 1

Related Questions