r - 按行和列名称以及按组合并两个数据框

标签 r merge

我有两个数据框 df1 和 df2,如下所示:

 df1<- data.frame(year, week, X1, X2)
 df1
  year week X1 X2
1 2010    1  2  3
2 2010    2  8  6
3 2011    1  7  5
 
 firm<-c("X1", "X1", "X2")
 year <- c(2010,2010,2011)
 week<- c(1, 2, 1)
 cost<-c(10,30,20)
 
 df2<- data.frame(firm,year, week, cost)
 df2
  firm year week cost
1   X1 2010    1   10
2   X1 2010    2   30
3   X2 2011    1   20
我想合并这些,所以最终结果(即 df3)如下所示:
df3 
  firm  year week cost Y 
1  X1   2010   1   10  2 
2  X1   2010   2   30  8 
3  X2   2011   1   20  5
其中“Y”是一个新变量,它反射(reflect)了在 df1 中找到的特定年份和周的 X1 和 X2 的值。
有没有办法在 R 中做到这一点?预先感谢您的回复。

最佳答案

我们可以将第一个数据集 reshape 为“长”格式,然后与第二个数据进行连接

library(dplyr)
library(tidyr)
df1 %>% 
 pivot_longer(cols = X1:X2, values_to = 'Y', names_to = 'firm') %>% 
 right_join(df2)
-输出
# A tibble: 3 x 5
#   year  week firm      Y  cost
#  <dbl> <dbl> <chr> <int> <dbl>
#1  2010     1 X1        2    10
#2  2010     2 X1        8    30
#3  2011     1 X2        5    20
数据
df1 <- structure(list(year = c(2010L, 2010L, 2011L), week = c(1L, 2L, 
1L), X1 = c(2L, 8L, 7L), X2 = c(3L, 6L, 5L)), class = "data.frame", 
row.names = c("1", 
"2", "3"))

df2 <- structure(list(firm = c("X1", "X1", "X2"), year = c(2010, 2010, 
2011), week = c(1, 2, 1), cost = c(10, 30, 20)), class = "data.frame", 
row.names = c(NA, 
-3L))

关于r - 按行和列名称以及按组合并两个数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64377697/

相关文章:

python - 从 Python 3.1.1 到 R 的最佳接口(interface)是什么?

减少范围ggplot y轴而不减少显示数据的范围

GitFlow : Properly Testing Release Branches & Master

javascript - 如何使用合并数组到d3可折叠树

git merge命令使用

python - 如何在Python中将数组与其数组元素合并?

r - 使用ggplot2绘制时间序列数据

r - 根据首次注册和最近值转换 NA 值

r - 使用 R 选择列中组内的前 N ​​个值

java - 如何合并多个pdf