【问题标题】:Counting columns that match between several data frames计算多个数据框之间匹配的列
【发布时间】:2019-03-07 09:23:50
【问题描述】:

我有几个数据框,其中有一些列匹配(在名称中),我想知道有多少。我现在正在使用这个函数来合并它们:

dflist <- list(d1, d2)
Reduce(function(x, y) merge(x, y, all=TRUE), dflist, accumulate=FALSE)

但我不知道有多少匹配,直到我查看它。或者,我想删除不匹配的列,而不是用 NA 填充。

编辑,添加示例:

d1 = mtcars
d2 = mtcars[, 1:4]
d3 = mtcars[, 3:5]
dflist = list(d1,d2,d3)

dflist <- list(d1, d2)
Reduce(function(x, y) merge(x, y, all=TRUE), dflist, accumulate=FALSE

【问题讨论】:

  • 嗨,欢迎来到 SO。请确保提供可重现的示例和预期的输出,以便其他人更容易帮助您。关于您的问题,使用Reduce 是正确的,但您可以通过函数intersect 轻松获取常用字段。所以像Reduce(function(...)intersect(names(...)), list(your_dataframes)) 这样的东西应该给你常见的列。

标签: r dataframe merge data-manipulation


【解决方案1】:

这是一个例子:

d1 = mtcars
d2 = mtcars[, 1:4]
d3 = mtcars[, 3:5]
dflist = list(d1,d2,d3)

现在获取 df 列表中匹配的列名:

Reduce(intersect, lapply(dflist, names))
# [1] "disp" "hp" 

然后您可以仅使用选定的公共列继续合并过程,例如使用:

common_cols = Reduce(intersect, lapply(dflist, names))

Reduce(function(...) merge(..., all=TRUE), 
       lapply(dflist, function(x) x[, common_cols, drop=FALSE]))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多