【问题标题】:how can write sqlQuery in R under the condition with sub value如何在具有子值的条件下在 R 中编写 sqlQuery
【发布时间】:2023-01-30 22:24:39
【问题描述】:
info <- paste("select count (*) as total
                from ANNUAL_CROP a
                where a.CROP_TYPE='Rye' and a.GEO = 'Canada'
                and a.YEAR = '%1968' ")
query <- sqlQuery(conn,info,believeNRows = FALSE)
query

请问如何在子值条件下在 R 中编写 sqlQuery,原始数据集将年份变量作为字符,我需要查询 CROP_TYPE='Rye' 和 a.GEO = 'Canada' 的行总数 和 a.YEAR = 1968

这是原始数据集 Annual_crops 的样本

【问题讨论】:

  • 如果我理解正确的话,你想将你的 SQL 查询“翻译”成 R 代码,对吧?
  • 有关执行此操作的 R 代码,请参阅summarize by group。我的猜测(我没有花时间转录你的图片数据,请只提供图片,meta.stackoverflow.com/a/285557(和xkcd.com/2116)),类似于with(mtcars, tapply(disp, list(cyl, gear), FUN = length))dplyr::count(mtcars, cyl gear)

标签: sql r


【解决方案1】:

如果我理解正确的话,这是一种可能的解决方案:

# dummy data read with OCR from your picture
mydf <- data.table::fread("CD_ID    YEAR    CROP_TYPE   GEO SEEDED_AREA HARVESTED_AREA  PRODUCTION  AVG_YIELD
2   31/12/1965  Barley  Saskatchewan    708000  708000  1415000 2000
5   31/12/1965  Canola  Saskatchewan    224600  224600  242700  1080
8   31/12/1965  Rye Saskatchewan    166000  166000  224000  1350
11  31/12/1965  Wheat   Saskatchewan    7486000 7486000 10886000    1455
14  31/12/1966  Barley  Saskatchewan    913000  913000  1981000 2170
17  31/12/1966  Canola  Saskatchewan    295800  295800  288000  975
20  31/12/1966  Rye Saskatchewan    161000  161000  228600  1420
23  31/12/1966  Wheat   Saskatchewan    7853000 7853000 14615000    1860")


library(dplyr)
# filter with conditions (altered to get a non NULL result from the dummy data (year is extracted by using last four characters from date string)
dplyr::filter(mydf, CROP_TYPE == 'Rye' & GEO == 'Saskatchewan' & stringr::str_sub(YEAR, -4, -1) == 1965) %>%
    # count 
    dplyr::count(name = "TOTAL")

   TOTAL
1:     1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-05
    • 2020-09-10
    • 2023-01-30
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多