Join two dataframes before exporting as .csv files

心不动则不痛 提交于 2019-12-04 08:42:44

If your end goal is an Excel spreadsheet, I'd look into some of the tools available in R for directly writing an xls file. Personally, I use the XLConnect package, but there is also xlsx and also several write.xls functions floating around in various packages.

I happen to like XLConnect because it allows for some handy vectorization in situations just like this:

require(XLConnect)

#Put your data frames in a single list
# I added two more copies for illustration
dfs <- list(df1,df2,df1,df2)

#Create the xls file and a sheet
# Note that XLConnect doesn't seem to do tilde expansion!
wb <- loadWorkbook("/Users/jorane/Desktop/so.xls",create = TRUE)
createSheet(wb,"Survey")

#Starting row for each data frame
# Note the +1 to get a gap between each
n <- length(dfs)
rows <- cumsum(c(1,sapply(dfs[1:(n-1)],nrow) + 1))

#Write the file
writeWorksheet(wb,dfs,"Survey",startRow = rows,startCol = 1,header = FALSE)
#If you don't call saveWorkbook, nothing will happen
saveWorkbook(wb)

I specified header = FALSE since otherwise it will write the column header for each data frame. But adding a single row at the top in the xls file at the end isn't much additional work.

As James commented, you could use

merge(df1, df2, by="a")

but that would combine the data horizontally. If you want to combine them vertically you could use rbind:

rbind(df1, df2, df3,...)

(Note: the column names need to match for rbind to work).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!