微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何将数据框从R导出到excel并用空行将其分隔

如何解决如何将数据框从R导出到excel并用空行将其分隔

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

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

我也不能使用软件包“ xlsx”和“ XLConnect”,因为它们给我带来了与Java有关的问题。

欢迎任何帮助。

数据框的第一个列表:

listofdfs <- list(x <- data.frame("y"=c(2009,2010,2011),"b"=c(35,30,20)),y <- data.frame("y"=c(2009,"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,"x_1"=c(35,20),"x_2"=c(1,2,0),"x_3"=c(6,3),"x_4"=c(12,5,8)),"x_1"=c(6,40),"x_2"=c(3,9,12),"x_4"=c(8,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工作表上获取表格:

enter image description here

enter image description here

解决方法

一次出现一个问题:

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。出色的写作

如果您尝试过像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,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")

输出文件: enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。