【问题标题】:ifelse & grepl commands when using dplyr for SQL in-db operations将 dplyr 用于 SQL in-db 操作时的 ifelse 和 grepl 命令
【发布时间】:2015-03-29 13:44:41
【问题描述】:

在R数据帧上运行的dplyr中,很容易运行

df <- df %>% 
    mutate(income_topcoded = ifelse(income > topcode, income, topcode)

我现在正在处理一个大型 SQL 数据库,使用 dplyr 向 SQL 服务器发送命令。当我运行相同的命令时,我回来了

Error in postgresqlExecStatement(conn, statement, ...) : 
RS-DBI driver: (could not Retrieve the result : ERROR:  
function ifelse  (boolean, numeric, numeric) does not exist
HINT:  No function matches the given name and argument types. You may need to add explicit type casts.

您建议如何实现ifelse() 语句?我对 PivotalR 中的某些东西很好(它似乎支持ifelse(),但我不知道如何将它与 dplyr 集成,并且在 SO 上找不到任何示例),一些我可以使用的 SQL 语法in-line here,或者我不知道的 dplyr 的某些功能。

(我有同样的问题,我想将grepl() 用作数据库内操作,但我不知道该怎么做。)

【问题讨论】:

  • 您能否重新表述您的问题,使其成为一个具体的编程问题?就目前而言,它很有可能被关闭为题外话(寻找工具,教程......)。
  • 您好 Roman,感谢您的提示!只好重写了。如果我以后有“寻找工具”形式的问题,你会建议我在哪里发布?
  • 我真的不知道。也许是处理类似主题的邮件列表?我通常只是在 SO 上进行互联网搜索或在 R 聊天室中提问。

标签: sql r postgresql dplyr


【解决方案1】:

根据@hadley 对this thread 的回复,您可以在dplyr 的数据库内数据帧上的mutate() 内使用SQL 样式的if() 语句:

df <- df %>% 
    mutate( income_topcoded = if (income > topcode) income else topcode)

就使用grepl() 而言......好吧,你不能。但是你可以使用 SQL like 操作符:

df  <- df %>%
    filter( topcode %like% "ABC%" )

【讨论】:

    【解决方案2】:

    我遇到了类似的问题。我能做的最好的就是按照您的建议使用数据库内操作:

    topcode <- 10000
    queryString <- sprintf("UPDATE db.table SET income_topcoded = %s WHERE income_topcoded > %s",topcode,topcode)
    dbGetQuery(con, queryString)
    

    在我的例子中,我使用带有 dplyr 的 MySQL,但它无法将我的 ifelse() 转换为有效的 SQL。

    【讨论】:

    • 这很干净,我会继续使用它。谢谢! (不给它检查,因为我仍然希望 dplyr 的创建者将来会构建此功能)
    猜你喜欢
    • 2015-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-06
    • 2018-12-12
    • 1970-01-01
    • 2017-02-23
    相关资源
    最近更新 更多