且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

合并具有不同行数和不同列数的数据框

更新时间:2023-12-02 14:48:34

如果A和B是两个输入数据框,这里有一些解决方案:

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

1) 合并无论 A 还是 B 有更多行,此解决方案都有效.

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]

如果 A 和 B 具有默认行名,即 1、2、...,或者它们具有一致的行名,则前两个参数可以分别替换为 A 和 B.即 merge(A, B, 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"))

然后:

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

给出:

  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) 一个等效的变体是:

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

2) cbind.zoo 这个解决方案假设 A 有更多的行并且 B 的条目都是相同的类型,例如都是数字.A 不受限制.这些条件在问题的数据中成立.

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)))