kim1298
kim1298

Reputation: 41

Using write.xlsx to write different data on different sheets in one file by for loop in r

I am trying to write each country's data on each sheet named with that country in one xlsx file. I am using xlsx package in r. I have tried

  for (i in 1:noctry) {
     write.xlsx(tab110rev[i,,], file="table.xlsx", sheetName = countrylist[i],
              col.names=FALSE, row.names=FALSE)  
}

noctry stands for number of countries and its 53
countrylist is a list of countries with country codes which are numbers.
tab110rev is an array that has the structure of array(value, c(country, industry, year))

The problem with this is that it only produces a xlsx file with just one sheet which contains the last country. There should be 53 sheets, not just one. I think the for-loop is overwriting instead of cumulating the result but I have no idea to fix this.

Upvotes: 1

Views: 6164

Answers (1)

Sean Lin
Sean Lin

Reputation: 815

I guess append = T should fix your problem. Try this:

for (i in 1:noctry) {
     write.xlsx(tab110rev[i,,], file="table.xlsx", sheetName = countrylist[i],
                col.names=FALSE, row.names=FALSE, append = T)  
}

Upvotes: 6

Related Questions