[英]Merge 2 tables to create 1 table: Same rows, different columns in R
我有兩個具有相同行的表,但它們每個都有不同的列。 是否可以將它們合並在一起? 我正在使用kabbleExtra
包來輸出表格。
18-24 25-34 35-44 45-54 55-64 65-74 75+ Total
Democrat 11.8 18.4 14.2 7.1 6.2 4.5 2.1 64.3
Republican 3.1 5.0 4.0 5.4 5.3 3.5 1.7 28.0
Other 2.0 0.9 1.2 2.1 0.7 0.6 0.2 7.7
Total 17.0 24.3 19.4 14.5 12.2 8.6 4.1 100.0
White Latino Asian African-American Other Total
Democrat 25.2 22.4 10.0 2.2 5.2 65.1
Republican 14.4 7.2 2.8 0.4 2.0 26.8
Other 2.5 4.1 0.9 0.0 0.6 8.1
Total 42.2 33.7 13.7 2.6 7.8 100.0
預期輸出應如下所示:
Ethnicity Age
White Latino Asian African-American Other Total 18-24 25-34 35-44 45-54 55-64 65-74 75+ Total
Democrat 25.2 22.4 10.0 2.2 5.2 65.1 11.8 18.4 14.2 7.1 6.2 4.5 2.1 64.3
Republican 14.4 7.2 2.8 0.4 2.0 26.8 3.1 5.0 4.0 5.4 5.3 3.5 1.7 28.0
Other 2.5 4.1 0.9 0.0 0.6 8.1 2.0 0.9 1.2 2.1 0.7 0.6 0.2 7.7
Total 42.2 33.7 13.7 2.6 7.8 100.0 17.0 24.3 19.4 14.5 12.2 8.6 4.1 100.0
我們可以使用 dplyr 合並表:
> df1 %>% rownames_to_column('party') %>%
+ inner_join(df2 %>% rownames_to_column('party'), by = 'party') %>% column_to_rownames('party')
18-24 25-34 35-44 45-54 55-64 65-74 75+ Total.x White Latino Asian African-American Other Total.y
Democrat 11.8 18.4 14.2 7.1 6.2 4.5 2.1 64.3 25.2 22.4 10.0 2.2 5.2 65.1
Republican 3.1 5.0 4.0 5.4 5.3 3.5 1.7 28.0 14.4 7.2 2.8 0.4 2.0 26.8
Other 2.0 0.9 1.2 2.1 0.7 0.6 0.2 7.7 2.5 4.1 0.9 0.0 0.6 8.1
Total 17.0 24.3 19.4 14.5 12.2 8.6 4.1 100.0 42.2 33.7 13.7 2.6 7.8 100.0
使用的數據:
> df1
18-24 25-34 35-44 45-54 55-64 65-74 75+ Total
Democrat 11.8 18.4 14.2 7.1 6.2 4.5 2.1 64.3
Republican 3.1 5.0 4.0 5.4 5.3 3.5 1.7 28.0
Other 2.0 0.9 1.2 2.1 0.7 0.6 0.2 7.7
Total 17.0 24.3 19.4 14.5 12.2 8.6 4.1 100.0
> df2
White Latino Asian African-American Other Total
Democrat 25.2 22.4 10.0 2.2 5.2 65.1
Republican 14.4 7.2 2.8 0.4 2.0 26.8
Other 2.5 4.1 0.9 0.0 0.6 8.1
Total 42.2 33.7 13.7 2.6 7.8 100.0
>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.