合并 r 中具有相同行名的 2 个数据帧

merge 2 dataframes in r with same row names

我有 2 个数据框,我想将它们合并为一个数据框,每个数据框对应于彼此的行名称值。如果您能告诉我如何将它们映射到绘图(ggplot2 或绘图)上,将不胜感激。


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")

有了merge,我们就可以把by当成row.names

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

如果我们需要绘图,我们可以使用base R barplot

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

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()

-输出