简体   繁体   English

如何将多个数据框合并到一个表中并导出到Excel?

[英]How to merge multiple data frame into one table and export to Excel?

I would like to merge a few data frame into one table, and export to Excel. 我想将几个数据框合并到一个表中,然后导出到Excel。 data frame is generated as below. 数据帧生成如下。

sex <- c("male","female")
count1 <- c(304,410)
df.sex <- data.frame(sex,count1)
df.sex[,"per"] <- df.sex$count1/sum(df.sex$count1)

agegp <- c("<=24","25-29","30-34","35-39")
count2 <- c(204,250,125,135)
df.agegp <- data.frame(agegp,count2)
df.agegp[,"per"] <- df.agegp$count2/sum(df.agegp$count2)

df.sex
sex count1       per
male    304 0.4257703
female    410 0.5742297

df.agegp
agegp count2       per
<=24    204 0.2857143
25-29    250 0.3501401
30-34    125 0.1750700
35-39    135 0.1890756

Since the first column of the two df are different, I could not rbind them and export to Excel. 由于两个df的第一列不同,因此我无法rbind它们并导出到Excel。

What I would like to generate is a table like below and export it to Excel. 我想生成的是一个如下表,并将其导出到Excel。

Can anyone help? 有人可以帮忙吗?

       count    percentage
sex     
male    304     0.4257703
female  410     0.5742297
agegp       
<=24    204     0.2857143
25-29   250     0.3501401
30-34   125     0.1750700
35-39   135     0.1890756

How about that ? 那个怎么样 ?

sink(file = "mergedPrinting.csv")

cat("First Frame:\n") 
write.csv(df.agegp, row.names = F)

cat("--------\n")

cat("Second Frame:\n")
write.csv(df.sex, row.names = F)

sink()

在此处输入图片说明

There are two EXCEL import/export R-packages I know of, both let you define the top left cell in which to begin writing your data.frame and wether to use a header. 我知道有两个EXCEL导入/导出R包,它们都可以让您定义开始写入data.frame的左上方单元格,并且还可以使用标头。

In your case I'd write the labels, count, percentage, sex, agegp, as single values into the cells and then write the two data.frames with rownames but no columnnames to the right position. 在您的情况下,我会将标签,计数,百分比,性别,agegp作为单个值写入单元格,然后将两个具有行名但没有列名的data.frames写入正确的位置。

See the vignette of both packages on how to open/create an EXCEL-file for writing and for the functions to write data.frames. 有关如何打开/创建用于写入的EXCEL文件以及用于写入data.frames的函数,请参见两个程序包的小插图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM