6

I have around 30 different data frames in r and I want them to be in one Excel sheet, with the dataframe name as well.

For output I'm looking for something like this:

dfname1
col1    col2
  x        x
  x        x
dfname2
col1    col3
  x        x

How should I do this as an iterative process?

4

1 Answer 1

8

Sounds like a bad idea to intersperse data frame names with data in the same worksheet, but that's up to you.

Anyway, use openxlsx. Here's a way to do it:

dfname1 <- data.frame(col1 = c("x", "x"), col2 = c("x", "x"), stringsAsFactors = FALSE)
dfname2 <- data.frame(col1 = c("x"), col3 = c("x"), stringsAsFactors = FALSE)

df_list <- list(dfname1=dfname1,
                dfname2=dfname2)

library(openxlsx)

wb <- createWorkbook()
addWorksheet(wb, "Foo")

curr_row <- 1
for(i in seq_along(df_list)) {
  writeData(wb, "Foo", names(df_list)[i], startCol = 1, startRow = curr_row)
  writeData(wb, "Foo", df_list[[i]], startCol = 1, startRow = curr_row+1)
  curr_row <- curr_row + nrow(df_list[[i]]) + 2
}

saveWorkbook(wb, "bar.xlsx")

This gives you (literally) what you asked for.

Sign up to request clarification or add additional context in comments.

1 Comment

That works a charm. But why would it be a bad idea "intersperse data frame names with data in the same worksheet"? I've been doing it to kinda concatenate lots of statistics tests and never saw a problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.