【问题标题】:R: finding mismatched column names before mergingR:在合并之前查找不匹配的列名
【发布时间】:2019-10-19 05:25:23
【问题描述】:

我有大量数据框要合并。每个都有数百列。我想在执行此操作之前识别所有不匹配的列名。到目前为止,我可以生成一个不匹配列表,但格式很糟糕,我不太清楚如何判断它们来自哪个数据框。

#create data
df1 <- data.frame("col1" = 3:4, "Age" = c(22,16), "Name" = c("James","Jim"))
df2 <- data.frame("col1" = 3:4, "Age" = c(18,19), "Name" = c("Mike","Mia"))
df3 <- data.frame("mismatch_col_name_1" = 1:2, "Age" = c(21,15), "name" = c("John","Dora"))
df4 <- data.frame("mismatch_col_name_2" = 1:2, "Age" = c(21,15), "Name" = c("John","Dora"))
files <- list(df1, df2, df3, df4)

# find mismatched column names
mismatches <- NULL
for (i in 1:(length(files) - 1)) {
  mismatches <- c(mismatches, setdiff(colnames(files[[i]]), colnames(files[[i+1]])))
}
mismatches <- c(mismatches, setdiff(colnames(files[[length(files)]]), colnames(files[[1]])))
print(mismatches)

[1] "col1"                "Name"                "mismatch_col_name_1" "name"               
[5] "mismatch_col_name_2"

所需的输出类似于:

“df3”“mismatch_col_name_1”“名称”

“df4”“mismatch_col_name_2”“名称”

甚至是 df 名称和列号。对任何解决方案或更好的方法感兴趣。

【问题讨论】:

  • 我们能否确信列的位置在所有文件中始终保持一致? (例如,任何看起来像 name 的东西总是第三列??)你知道至少一个文件的所有正确的列名应该是什么吗? (即在本例中,我们事先知道 col1AgeName
  • 我认为这里的关键问题是@Jas 提出的最后一个问题,即您是否有所需/正确列名的主列表,或者您是否想寻找差异,句号?

标签: r merging-data


【解决方案1】:

这是一种方法,可以让您找到一个列表(在 R 意义上),其中包含每个文件的不匹配项。它的前提是您知道用于比较每个文件的“真实”名称集。

lapply(files, function(x) {

    # vector of desired names
    master <- c('col1', 'Age', 'Name')

    # use 'match' to compare this df's names to the master. the order of the
    # cols won't matter; if the name in x appears in master, 'match' will return
    # an integer indicating the position of the col with that name in x.
    comparison <- match(names(x),  master)

    # if all col names in x appear in master, you get all integers, so: NULL
    if (!any(is.na(comparison))) {

        NULL

    # if names in x don't appear in master, you get an NA from 'match', so here you
    # create a vector of the names in x that aren't in master. You could also capture
    # their position here if that's helpful.
    } else {

        mismatches <- names(x)[which(is.na(comparison))]

    }

})

结果:

[[1]]
NULL

[[2]]
NULL

[[3]]
[1] "mismatch_col_name_1" "name"               

[[4]]
[1] "mismatch_col_name_2"

您可以通过多种方式组织或总结此列表的内容,但这主要是格式问题。

【讨论】:

  • 非常感谢,我认为这种方法会奏效。此外,是否有一种方法可以处理主列表中缺少列(即其中一个数据集的列数较少)的情况?
  • 这种方法在这种情况下也很有效。尝试match(c(1,2), rev(1:4)) 看看当您匹配的对象的元素少于参考对象时会发生什么。
猜你喜欢
  • 1970-01-01
  • 2015-05-01
  • 2015-11-22
  • 1970-01-01
  • 2020-02-13
  • 1970-01-01
  • 2021-08-29
  • 2020-02-05
  • 2020-03-23
相关资源
最近更新 更多