如何将数据帧从 R 导出到 excel 并用空行分隔它们

how to export dataframes from R to excel and separate them by an empty row

我应该附加存储在 R 中不同列表中的数据帧,并用空行分隔它们(在 excel 文件中)。

我无法将来自不同列表的数据帧绑定到一个列表中,因为它们的列数不同。

我不能同时使用软件包 'xlsx' 和 'XLConnect',因为它们给我带来了与 Java.

相关的问题

欢迎任何帮助。

第一个dataframe列表:

listofdfs <- list(x <- data.frame("y"=c(2009,2010,2011),"b"=c(35,30,20)), y <- data.frame("y"=c(2009,2010,2011), "b"=c(6,21,40)) )

label <- c("Red","Green")

listofdfs <- setNames(listofdfs, label)

$Red
     y  b
1 2009 35
2 2010 30
3 2011 20

$Green
     y  b
1 2009  6
2 2010 21
3 2011 40

第二个数据帧列表(比之前的列多):

listofdfs_2 <- list(x <- data.frame("y"=c(2009,2010,2011),"x_1"=c(35,30,20), "x_2"=c(1,2,0), "x_3"=c(6,0,3), "x_4"=c(12,5,8)), y <- data.frame("y"=c(2009,2010,2011), "x_1"=c(6,21,40), "x_2"=c(3,5,0), "x_3"=c(6,9,12), "x_4"=c(8,5,1)) )

label <- c("Red","Green")

listofdfs_2 <- setNames(listofdfs_2, label)

$Red
     y x_1 x_2 x_3 x_4
1 2009  35   1   6  12
2 2010  30   2   0   5
3 2011  20   0   3   8

$Green
     y x_1 x_2 x_3 x_4
1 2009   6   3   6   8
2 2010  21   5   9   5
3 2011  40   0  12   1

我想以这种方式获取相同的 excel sheet 表格:

一次一个问题:

1.附加具有不同列的数据帧

rbind(df1,df2) #this fails if they do not have the same columns

library(dplyr)
df1 %>%
    bind_rows(df2) #this works even with different columns

#including an empty row
df1 %>%
    bind_rows(df_empty) %>% #pre-create a df with one "check" column and an empty row
    bind_rows(df2)

2.Writing 到 excel

如果您尝试过 foreign 等不同的软件包,只需另存为 csv 即可在 Excel.

中打开
write.csv(df_result,"result.csv")

使用 openxlsx,我希望它比你提到的其他软件包更适合你,你可以这样做:

library(openxlsx)

# create your workbook
mywb <- createWorkbook() 

# create the sheets you need based on the first list of tables
for (sheetName in names(listofdfs)){
    addWorksheet(mywb , sheetName )
}

# get all your lists of tables in a single list
l_listOfDF <- mget(ls(pattern="listofdf"))

# initiate the index of the row where you will want to start writing (one per sheet)
startR <- rep(1, length(listofdfs)) ; names(startR) <- names(listofdfs)

# loop over the lists of tables using index and then over the elements / sheets using their names
for(N_myListOfDF in seq(l_listOfDF)){

  for(pageName in names(l_listOfDF[[N_myListOfDF]])){

    # write the name/number of your table in the correct sheet, at the correct row
    writeData(mywb, sheet=pageName, startRow=startR[pageName], paste0("Table ", N_myListOfDF, "."))

    # write your data in the correct sheet at the correct row (the one after the name)
    writeData(mywb, sheet=pageName, startRow=startR[pageName]+1, l_listOfDF[[N_myListOfDF]][[pageName]])
    
    # update the row number (the + 3 is to leave space for name of table, headers and blank row
    startR[pageName] <- startR[pageName]+nrow(l_listOfDF[[N_myListOfDF]][[pageName]]) + 3

  }
}

# save your workbook in a file
saveWorkbook(mywb , "myfile.xlsx")

输出文件: