简体   繁体   中英

How to avoid R errors while writing queries with single and double quotes

I have a problem while writing Query at R to select Data from Presto Database. I used the next code with

    library(DBI)
    library(dplyr)
    library(RPresto)
    res = dbSendQuery(con, " select RESPONDENT as Respondent,RESPONSE_DATE 
    as Date,
    MAX(CASE
    WHEN QUESTION_ID = '18' AND RESPONSE_ID ='5' THEN 'Very Satisfied'
    WHEN QUESTION_ID = '18' AND RESPONSE_ID ='4' THEN 'Satisfied'
    WHEN QUESTION_ID = '18' AND RESPONSE_ID ='3' THEN 'Neutral'
    WHEN QUESTION_ID = '18' AND RESPONSE_ID ='2' THEN 'Dissatisfied'
    WHEN QUESTION_ID = '18' AND RESPONSE_ID ='1' THEN 'Very Dissatisfied' 
    ELSE NULL END) AS "How was our service looks based on your last meal?"
    from surveytable
    group by 1,2")

Errors appeared at R like

    Error: unexpected numeric constant in:
    "                WHEN QUESTION_ID = '18' AND RESPONSE_ID ='2' THEN 
    'Dissatisfied' 
    WHEN QUESTION_ID = '18' AND RESPONSE_ID ='1' THEN 'Very Dissatisfied' 
    ELSE NULL END) AS "7."
    >                 from dev_bi.Checkmarket_survey_78995
    Error: unexpected symbol in "                from 
    dev_bi.Checkmarket_survey_78995"
    >                 group by 1,2
    Error: unexpected symbol in "                group by"
    >                 limit 1")
    Error: unexpected numeric constant in "                limit 1"

You can prepend every double quote in you query with backslash. See this:

query <- " select RESPONDENT as Respondent,RESPONSE_DATE 
    as Date,
    MAX(CASE
    WHEN QUESTION_ID = '18' AND RESPONSE_ID ='5' THEN 'Very Satisfied'
    WHEN QUESTION_ID = '18' AND RESPONSE_ID ='4' THEN 'Satisfied'
    WHEN QUESTION_ID = '18' AND RESPONSE_ID ='3' THEN 'Neutral'
    WHEN QUESTION_ID = '18' AND RESPONSE_ID ='2' THEN 'Dissatisfied'
    WHEN QUESTION_ID = '18' AND RESPONSE_ID ='1' THEN 'Very Dissatisfied' 
    ELSE NULL END) AS \"How was our service looks based on your last meal?\"
    from surveytable
    group by 1,2"
cat(query)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM