【问题标题】:Data.Table R: error merging greater than four DTs with Reduce and mergeData.Table R:使用Reduce和merge合并大于四个DT时出错
【发布时间】:2020-07-22 15:57:52
【问题描述】:

例如,我有一个包含 7 个具有相同维度 (1 74 2) 和列名(“变量”和“V1”)的 dts 的列表;

> head(dt1)
    variable          V1
1:      A         4.213668
2:      B      1474.040190
3:      C         4.445173
4:      D        76.960665
5:      E        81.796707
6:      F       215.312311

根据 Michael Ohlrogge MergedDT = Reduce(function(...) merge(..., all = TRUE), List_of_DTs) revisions of Merging multiple data.tables 的脚本,我想出了以下内容;

list<-list(dt1, dt2, ....dt7)

merged<-Reduce(function(...) merge(..., by="variable", all=T, allow.cartesian=T),list)

这适用于 4 个但超过 4 个的列表,我收到此错误,

error in merge.data.table(..., by = "variable", no.dups = F, all = T,  : 
  x has some duplicated column name(s): V1.k1,V1.k2. Please remove or rename the duplicate(s) and try again.
In addition: Warning message:
In merge.data.table(..., by = "variable", no.dups = F, all = T,  :
  column names 'V1.k1', 'V1.k2' are duplicated in the result

如果能解决这个问题,我将不胜感激。

【问题讨论】:

  • 您能否重命名所有列表元素中的“V1”列,即Map(setnames, list, 'V1', paste0('V', seq_along(list))),然后运行Reduce
  • 请让您的示例可重现
  • @akrun,更改“V1”解决了问题。您能否向我展示一个脚本来更改多个(数百个)data.tables 而不是列表中的“V1”?谢谢。

标签: r merge data.table


【解决方案1】:

如果我们需要在多个数据集中更改它,请将它们加载到带有mgetlist 中。在这里,我们假设数据集对象名称以“dt”开头,后跟一些数字

library(data.table)
lst1 <- mget(ls(pattern = '^dt\\d+$'))
lst1 <- Map(setnames, lst1, 'V1', paste0('V', seq_along(list)))

【讨论】:

    猜你喜欢
    • 2014-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-11
    • 1970-01-01
    • 2020-07-16
    • 2019-03-19
    • 1970-01-01
    相关资源
    最近更新 更多