Jack_Carver
Jack_Carver

Reputation: 77

R - write.xlsx via lapply

my dataframe is this

dt <- 
  data.frame(
     y = c(2018, 2018, 2018, 2019),
     m = c(1, 2, 3, 8),
     id = c(7, 2, 9, 1)
  )

In reality it is much much bigger, id like to export it via write.xlsx, something like

write.xlsx(dt, “result.xlsx”)

But the thing is that my dataframe is so big, that I need to create separate file for each y(ear) and m(onth). Month+year combination should be also present in filename. I was thinking about some lapply code, bude I wasnt succsefull yet.

Result should be 1-2018 result.xlsx, 2-2018 result.xlsx etc

Upvotes: 0

Views: 172

Answers (2)

s_baldur
s_baldur

Reputation: 33498

Here is a way to use data.table for the task:

library(xlsx)
library(data.table)
setDT(dt)
dt[, write.xlsx(.SD, paste(m, y, "result.xlsx", sep="-")), by = .(y, m), .SDcols = names(dt)]

Upvotes: 0

Duck
Duck

Reputation: 39585

You can use mapply() to export and split() to create a list by some defined variable:

library(xlsx)
#Data
dt <- 
  data.frame(
    y = c(2018, 2018, 2018, 2019),
    m = c(1, 2, 3, 8),
    id = c(7, 2, 9, 1)
  )
#Only by year
L1 <- split(dt,dt$y)
#Only by month
L2 <- split(dt,dt$m)
#By year and month
L3 <- split(dt,paste(dt$y,dt$m))
#Export
mapply(write.xlsx,L1,file=paste0(names(L1),'.xlsx'),row.names=F)
mapply(write.xlsx,L2,file=paste0(names(L2),'.xlsx'),row.names=F)
mapply(write.xlsx,L3,file=paste0(names(L3),'.xlsx'),row.names=F)

If data is too heavy use openxlsx package.

Upvotes: 1

Related Questions