简体   繁体   中英

Merging different data frames with different columns in R

I tried with the following code:

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)

My results does not look promising, I would like to plot my data set without loosing any of them after the merging, because I want each data frame in a separated graph, but all the same in the same frame. Does any one have an idea about what what is wrong in my code?

I think you are just trying to bind the columns together based on both Phase and Year . The dplyr approach would be.

library(dplyr)

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

Edit

I now see with your gather that you are building a long format, so we'll switch to bind_rows to bring together.

newd <- bind_rows(other_df, code_df, test_df)

Your plot will now generate after changing that line.

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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