繁体   English   中英

合并R中不同列的不同数据框

[英]Merging different data frames with different columns in R

我尝试使用以下代码:

library(ggplot2)
library(dplyr)
library(tidyr)

other <- read.table(text='Phase Year    V14 V15
Other   2017    0.016488414 0.027183601
Other   2016    0.016937669 0.016937669
Other   2016    0.020214521 0.010313531
Other   2016    0.025205761 0.099279835
Other   2016    0.014341085 0.037596899
Other   2016    0.01622807  0.04254386', header=TRUE)


code <- read.table(text='Phase   Year    V5  V8  V19 V21
Code    2017    0.016488414 0.053921569 0.01114082  0.027183601
Code    2016    0.033197832 0.016937669 0.016937669 0.016937669', header=TRUE)

test <- read.table(text='Phase   Year    V6  V11 V20 V22
Test    2017    0.032531194 0.027183601 0.016488414 0.305258467
Test    2016    0.106368564 0.025067751 0.016937669 0.025067751', header=TRUE)

# tidy data
code_df <- code %>%
          gather(key, value, V5, V8, V19, V21)
test_df <- test %>%
          gather(key, value, V6, V11, V20, V22)
other_df <- other %>%
          gather(key, value, V14, V15)


newd <- merge(other_df, code_df, test_df, all=TRUE)
par(mfrow = c(1, 2))
ggplot(data=newd, aes(x=Year)) +
  geom_density(aes(group=Phase, color=Phase, fill=Phase, showguide=FALSE)) +
  ggtitle("Test")+
  xlab("Year")+
  ylab("Probability")+
  facet_wrap(~Phase, ncol=1)

我的结果看起来并不理想,我想在合并后不丢失任何数据的情况下绘制数据集,因为我希望每个数据框都在单独的图中,但在同一帧中都一样。 有人对我的代码有什么问题有想法吗?

我认为您只是想根据PhaseYear将列绑定在一起。 dplyr方法是。

library(dplyr)

df <- df1 %>%
  bind_cols(df2, by = c("Phase", "Year")) %>%
  bind_cols(df3, by = c("Phase", "Year"))

编辑

现在,随着您的聚集,我看到您正在构建一个长格式,因此我们将切换到bind_rows进行合并。

newd <- bind_rows(other_df, code_df, test_df)

现在,更改该线后将生成您的绘图。

在此处输入图片说明

暂无
暂无

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

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