r - 合并 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")
解决方案
有了merge
,我们可以使用by
asrow.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()
-输出
推荐阅读
- python-3.x - 删除超类的部分方法
- python - Python 3.5 装饰器和函数字段
- python - 如何在熊猫中切割连续变量
- javascript - 内联导入导出组件在热重载时抛出错误
- javascript - 将参数传递给 rhandsontable 中的自定义渲染器在 Shiny App 中不起作用
- three.js - Forge 查看器:如何在材质中禁用透明度
- c# - 虚拟路径问题
- r - 按特定日期访问 data.frame 子集会生成 NA
- jupyter-notebook - 如何从 Jupyter Notebook 制作精美的 PDF?
- xamarin - NSDictionary 到 Xamarin.iOS 中的 Json