【问题标题】:R- too many columns when using sqldf to join dataframesR-使用sqldf加入数据框时列太多
【发布时间】:2025-12-08 11:20:07
【问题描述】:

我正在尝试将两个数据框合并为一个。第一个df是acutedm11,有4682列,第二个是gwlfullflattened22,有4903列。我不能在这里发布数据,因为它太大并且包含敏感信息。我正在尝试根据 mrn=mrn_G 和日期差异 合并这两个 dfs

代码:

library(sqldf)
acutedm3 <- sqldf::sqldf("
    select acutedm11.*, gwlfullflattened22.*
    from acutedm11
       left join gwlfullflattened22 on acutedm11.mrn = gwlfullflattened22.mrn_G
        and gwlfullflattened22.EncounterDate_G between acutedm11.Date_m30 and acutedm11.Date_p30") %>%
  select(-Date_m30, -Date_p30)

错误:Error: too many columns on acutedm11

有没有更好的方法来合并/加入数据框?

【问题讨论】:

    标签: r


    【解决方案1】:
    1. 最大列数是 SQLite 中的编译时参数(包含在 RSQLite 包中)。您可以将限制重新设置得更高并重建该包。欲了解更多信息,请参阅:Maximum number of columns in a table for sqlite

    2. sqldf 还支持 4 种不同的后端:SQLiteH2MySQLPostgreSQL。尝试其他一种。

    例如,使用 H2 这不会给我任何错误。

    library(RH2)
    library(sqldf)
    
    nr1 <- 100
    nc1 <- 4682 
    df1 <- as.data.frame(matrix(seq_len(nr1*nc1), nr1))
    
    nr2 <- 100
    nc2 <- 4903
    df2 <- as.data.frame(matrix(seq_len(nr2*nc2), nr2))
    
    res <- sqldf("select * from df1 a
           left join df2 b on a.V1 = b.V1
            and a.V2 between b.V3 and b.V4")
    

    【讨论】:

    • 我正在使用 RStudio。我查看了您发送给我的指南,但没有任何关于如何增加 R 中的最大列数的说明。
    • 我通过输入 DSQLITE_MAX_COLUMN=1234567RSQLITE_MAX_COLUMN=1234567 增加了 R 中的最大列数。我仍然遇到同样的错误。如何在不下载任何内容的情况下使用 H2、MySQL 或 PostgreSQL?
    • 必须在 C 代码源中更改这些参数,然后重新构建 RSQLite。要使用 H2,请确保已安装 java,然后从 CRAN 安装 RH2 包。请务必阅读 ?sqldf 。
    • 感谢您提供示例代码。我试过了,得到了同样的错误。 Error: too many columns on acutedm11
    • 如果您遇到同样的错误,您可能仍在使用 SQLite 并且没有加载 RH2。将verbose=TRUE 参数添加到sqldf 以检查正在使用的数据库。