将数据框加入多个列表

时间:2019-06-01 14:29:38

标签: r

我有以下列表:

$df1
  x   y          z
1 a 145 2010-01-01
2 b  22 2010-02-01
3 c  33 2010-03-01

$df2
  x   y          z
1 d  45 2010-01-01
2 e  35 2010-02-01
3 f 633 2010-03-01

我还有一个数据框,如下所示:

    x   y          z
1 aty 451 2010-01-01
2 b43 452 2010-02-01
3 crf 343 2010-03-01

我正在尝试将dataframe列的datez合并到每个列表,因此预期的输出将类似于:

$df1
  x   y          z  x.1 y.1
1 a 145 2010-01-01  aty 451
2 b  22 2010-02-01  b43 452
3 c  33 2010-03-01  crf 343

$df2
  x   y          z  x.1 y.1
1 d  45 2010-01-01  aty 451
2 e  35 2010-02-01  b43 452
3 f 633 2010-03-01  crf 343

数据:

foo <- list(df1 = data.frame(x=c('a', 'b', 'c'),y = c(145,22,33), z=c("2010-01-01", "2010-02-01", "2010-03-01")), 
            df2 = data.frame(x=c('d', 'e', 'f'),y = c(45,35,633), z=c("2010-01-01", "2010-02-01", "2010-03-01")))


foo2 <- data.frame(x = c('aty', 'b43', 'crf'), y= c(451,452,343), z=c("2010-01-01", "2010-02-01", "2010-03-01"))

2 个答案:

答案 0 :(得分:2)

R的基本选项是将Map中的每个数据帧与merge一起使用foofoo2

Map(merge, foo, list(foo2), by = "z")

#$df1
#           z x.x y.x x.y y.y
#1 2010-01-01   a 145 aty 451
#2 2010-02-01   b  22 b43 452
#3 2010-03-01   c  33 crf 343

#$df2
#           z x.x y.x x.y y.y
#1 2010-01-01   d  45 aty 451
#2 2010-02-01   e  35 b43 452
#3 2010-03-01   f 633 crf 343

答案 1 :(得分:2)

我们可以使用tidyverse

library(tidyverse)
map(foo, inner_join, foo2, by = 'z')
#$df1
#  x.x y.x          z x.y y.y
#1   a 145 2010-01-01 aty 451
#2   b  22 2010-02-01 b43 452
#3   c  33 2010-03-01 crf 343

#$df2
#  x.x y.x          z x.y y.y
#1   d  45 2010-01-01 aty 451
#2   e  35 2010-02-01 b43 452
#3   f 633 2010-03-01 crf 343

或使用base R

lapply(foo, merge, foo2, by = 'z')
#$df1
#           z x.x y.x x.y y.y
#1 2010-01-01   a 145 aty 451
#2 2010-02-01   b  22 b43 452
#3 2010-03-01   c  33 crf 343

#$df2
#           z x.x y.x x.y y.y
#1 2010-01-01   d  45 aty 451
#2 2010-02-01   e  35 b43 452
#3 2010-03-01   f 633 crf 343