cbind 2 dataframes with different number of rows

前端 未结 3 1161
陌清茗
陌清茗 2020-11-30 10:25

I have two lists named h and g. They each contain 244 dataframes and they look like the following:

h[[1]]
   year  avg    hr   sal
         


        
3条回答
  •  眼角桃花
    2020-11-30 10:51

    Here is how you could do this with tidyverse tools:

    library(tidyverse)
    
    h <- list()
    g <- list()
    
    h[[1]] <- tribble(
      ~year,  ~avg, ~hr,  ~sal,
      2010,  0.300,  31,  2000,
      2011,  0.290,  30,  4000,
      2012,  0.275,  14,   600,
      2013,  0.280,  24,   800,
      2014,  0.295,  18,  1000,
      2015,  0.330,  26,  7000,
      2016,  0.315,  40,  9000
    )
    
    g[[1]] <- tribble(
      ~year,  ~pos,  ~fld,
       2010,   "A",   0.990,
       2011,   "B",   0.995,
       2013,   "C",   0.970,
       2014,   "B",   0.980,
       2015,   "D",   0.990
    )
    
    map2(h, g, left_join)
    

    Which produces:

    [[1]]
    # A tibble: 7 x 6
       year   avg    hr   sal pos      fld
            
    1  2010 0.3      31  2000 A      0.99 
    2  2011 0.290    30  4000 B      0.995
    3  2012 0.275    14   600 NA    NA    
    4  2013 0.28     24   800 C      0.97 
    5  2014 0.295    18  1000 B      0.98 
    6  2015 0.33     26  7000 D      0.99 
    7  2016 0.315    40  9000 NA    NA  
    

提交回复
热议问题