Using write.xlsx inside of a for in R

I have a very big database called "Duplicados_2010_2022" and I want to generate excel files disagreggated by a specific column. I want to subset the database by the column "SECRETARÍAS", because I need to see the data by each secretary (they are 92). I tried using the following expression:

Lista  <- levels(as.factor(Duplicados_2010_2022$SECRETARÍA))
for (i in Lista) {
  write.xlsx(Duplicados_2010_2022[Duplicados_2010_2022$SECRETARÍA==i,],i)
}

The problem is that when I asigned i as the file name, it does not include the .xlsx, therefore it exports the file, but not as an excel file. If somebody could suggest me a way for not doing the export 92 times, I would appreciate it.

Upvotes: 0

Views: 370

Answers (1)

thamirubs
thamirubs

Reputation: 26

Please try the following:

for (i in Lista) {
  write.xlsx(paste0(Duplicados_2010_2022[Duplicados_2010_2022$SECRETARÍA==i,], ".xlsx"), i)
}

The first argument of function write.xlsx is the file name, and the ".xlsx" extension was missing in the file name string. It must be specified.

Upvotes: 1

Related Questions