首页 > 解决方案 > 合并 r 中具有相同行名的 2 个数据帧

问题描述

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

标签: rdataframeplotmergerow-number

解决方案


有了merge,我们可以使用byasrow.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()

-输出

在此处输入图像描述


推荐阅读