Search code examples
rdataframeplotmergerow-number

merge 2 dataframes in r with same row names


I have 2 dataframes and I want to merge them into one dataframe each corresponding to eachother's row name values. If you could show me how to map them on a plot (ggplot2 or plot), that would be much appreciated.


df1:

structure(list(`12m yield` = c("4.72", "7.07", "3.08")), class = "data.frame", row.names = c("HUKX", 
"HRUB", "EUN"))

df2:

structure(list(Volatility101 = c(25.25353177644, 42.1628734949414, 
28.527736824123)), row.names = c("EUN", "HRUB", "HUKX"), class = "data.frame")

Solution

  • With merge, we can use the by as row.names

    out <- merge(df1, df2, by = 'row.names')
    

    If we need to plot, either we can use base R barplot

    barplot(`row.names<-`(as.matrix(out[-1]),
              out$Row.names), col = c('blue', 'green', 'red'), legend = TRUE)
    

    Or with tidyverse

    library(ggplot2)
    library(dplyr)
    library(tidyr)
    merge(df1, df2, by = 'row.names') %>% 
       rename(nm = 'Row.names') %>%  # // rename the column name
       type.convert(as.is = TRUE) %>%  # // some columns were not of the correct type
       pivot_longer(cols = -nm) %>% # // reshape to 'long' format
       ggplot(aes(x = name, y = value, fill = nm)) + # // plot as bar
            geom_col() + 
            theme_bw()
    

    -output

    enter image description here