cbind 2 dataframes with different number of rows

前端 未结 3 1158
陌清茗
陌清茗 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:44

    I think you should instead use merge:

    merge(df1, df2, by="year", all = T)
    

    For your data:

    df1 = data.frame(matrix(0, 7, 4))
    names(df1) = c("year", "avg", "hr", "sal")
    df1$year = 2010:2016
    df1$avg = c(.3, .29, .275, .280, .295, .33, .315)
    df1$hr = c(31, 30, 14, 24, 18, 26, 40)
    df1$sal = c(2000, 4000, 600, 800, 1000, 7000, 9000)
    df2 = data.frame(matrix(0, 5, 3))
    names(df2) = c("year", "pos", "fld")
    df2$year = c(2010, 2011, 2013, 2014, 2015)
    df2$pos = c('A', 'B', 'C', 'B', 'D')
    df2$fld = c(.99,.995,.97,.98,.99)
    

    cbind is meant to column-bind two dataframes that are in all sense compatible. But what you aim to do is actual merge, where you want the elements from the two data frames not be discarded, and for missing values you get NA instead.

提交回复
热议问题