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

gan*_*ong 6 sql postgresql r dplyr

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

df <- df %>% 
    mutate(income_topcoded = ifelse(income > topcode, income, topcode)
Run Code Online (Sandbox Code Playgroud)

我现在正在使用大型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.
Run Code Online (Sandbox Code Playgroud)

你会如何建议实施ifelse()声明?我对PivotalR中的东西很好(这似乎支持ifelse(),但我不知道如何将它与dplyr集成,并且在SO上找不到任何示例),我可以在线使用的一些SQL语法在这里,或者dplyr的一些我不知道的特征.

(我有同样的问题,我想grepl()用作in-db操作,但我不知道该怎么做.)

cra*_*lly 6

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

df <- df %>% 
    mutate( income_topcoded = if (income > topcode) income else topcode)
Run Code Online (Sandbox Code Playgroud)

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

df  <- df %>%
    filter( topcode %like% "ABC%" )
Run Code Online (Sandbox Code Playgroud)