sql - 使用 dplyr 进行 SQL in-db 操作时的 ifelse 和 grepl 命令

标签 sql r postgresql dplyr

在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 语法,或我不知道的 dplyr 的某些功能。

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

最佳答案

基于@hadley 对 this thread 的回复,您可以在 dplyr 的 in-db 数据帧上的 mutate() 中使用 SQL 样式的 if() 语句:

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

就使用 grepl() 而言……好吧,你不能。但是您可以使用 SQL like 运算符:

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

关于sql - 使用 dplyr 进行 SQL in-db 操作时的 ifelse 和 grepl 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29329851/

相关文章:

mysql - 将 SELECT 变量连接到不同的表列 |遵循建议

Select 中的 SQL 内联条件

MySQL从两列中选择日期范围数据

还原转换预处理插入符

c++ - 使用 RInside 阅读 R 控制台

MySQL count + rollup 对查询问题进行小计

R glm标准误差估计与SAS PROC GENMOD的差异

SQL;函数和 where 子句

sql - PostgreSQL Select where 多个 OR 语句

sql - Postgres 重复键错误代码