Merging data frames with different number of rows and different columns

前端 未结 1 1798
Happy的楠姐
Happy的楠姐 2021-01-01 05:37

I have two data frames with different number of columns and rows. I want to combine them into one data frame.

> month.saf
   Name NCDC    Year    Month            


        
1条回答
  •  無奈伤痛
    2021-01-01 06:22

    If A and B are the two input data frames, here are some solutions:

    1) merge This solutions works regardless of whether A or B has more rows.

    merge(data.frame(A, row.names=NULL), data.frame(B, row.names=NULL), 
      by = 0, all = TRUE)[-1]
    

    The first two arguments could be replaced with just A and B respectively if A and B have default rownames, i.e. 1, 2, ..., or if they have consistent rownames. That is, merge(A, B, by = 0, all = TRUE)[-1] .

    For example, if we have this input:

    # test inputs
    A <- data.frame(BOD, row.names = letters[1:6])
    B <- setNames(2 * BOD[1:2, ], c("X", "Y"))
    

    then:

    merge(data.frame(A, row.names=NULL), data.frame(B, row.names=NULL), 
      by = 0, all = TRUE)[-1]
    

    gives:

      Time demand  X    Y
    1    1    8.3  2 16.6
    2    2   10.3  4 20.6
    3    3   19.0 NA   NA
    4    4   16.0 NA   NA
    5    5   15.6 NA   NA
    6    7   19.8 NA   NA
    

    1a) An equivalent variation is:

    do.call("merge", c(lapply(list(A, B), data.frame, row.names=NULL), 
      by = 0, all = TRUE))[-1]
    

    2) cbind.zoo This solution assumes that A has more rows and that B's entries are all of the same type, e.g. all numeric. A is not restricted. These conditions hold in the data of the question.

    library(zoo)
    data.frame(A, cbind(zoo(, 1:nrow(A)), as.zoo(B)))
    

    0 讨论(0)
提交回复
热议问题