【问题标题】:merge 2 dataframes in r with same row names合并 r 中具有相同行名的 2 个数据框
【发布时间】:2021-03-11 21:25:43
【问题描述】:

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

【问题讨论】:

    标签: r dataframe plot merge row-number


    【解决方案1】:

    使用merge,我们可以将by 用作row.names

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

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

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

    -输出

    【讨论】:

    • 我在想更多的散点图,但感谢合并部分。
    猜你喜欢
    • 2017-05-18
    • 1970-01-01
    • 2021-03-30
    • 1970-01-01
    • 2013-12-08
    • 2020-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多