Filtering with sqldf in R when fields have quotation marks

342 Views Asked by At

I have a large sql db (7gbs), where the fields appear to have quotation marks in them.

For example:

res <- dbSendQuery(con, "
                   SELECT *
                   FROM master")

dbf2 <- fetch(res, n = 3)

dbClearResult(res)

Yields

 NPI                EntityTypeCode ReplacementNPI EmployerIdentificationNumber.EIN.
1 "1679576722"            "1"             ""                                ""
2 "1588667638"            "1"             ""                                ""
3 "1497758544"            "2"             ""                       "<UNAVAIL>"
  ProviderOrganizationName.LegalBusinessName. ProviderLastName.LegalName. ProviderFirstName
1                                          ""                     "WIEBE"           "DAVID"
2                                          ""                   "PILCHER"         "WILLIAM"
3    "CUMBERLAND COUNTY HOSPITAL SYSTEM, INC"                          ""                ""

I've been trying to get a smaller table by filtering on, say EntityTypeCode but I'm not getting any results. Here's an example of a query not getting anything, any advice? I think the issue is use of double quotes in the fields.

# Filter on State 
res <- dbSendQuery(npi2, "
                   SELECT * 
                   FROM master
                   WHERE (ProviderBusinessPracticeLocationAddressStateName = 'PA') 
                   ")

# Filter on State and type 
res <- dbSendQuery(npi2, "
                   SELECT * 
                   FROM master
                   WHERE (ProviderBusinessPracticeLocationAddressStateName = 'PA') AND 
                   (EntityTypeCode = '1') 
                   ")

1

There are 1 best solutions below

0
On BEST ANSWER

Escape the inner double quotes (ie, the ones in the cell) with a \.

res <- dbSendQuery(npi2, "
                   SELECT * 
                   FROM master
                   WHERE (ProviderBusinessPracticeLocationAddressStateName = '\"PA\"') AND 
                   (EntityTypeCode = '1') 
                   ")

This produces the following string:

                   SELECT * 
                   FROM master
                   WHERE (ProviderBusinessPracticeLocationAddressStateName = '"PA"')