使用循环从SQLite数据库获取数据的语法?

时间:2012-09-30 18:22:51

标签: r syntax

解决方案:

结合以下答案:

#First create a vector with all my dates

#Create a frame to hold the data
testdf = data.frame(sdci=rep("",1),stringsAsFactors=FALSE)

#needs library(lubridate) for month/year functions
library(lubridate)

#Loop and Add data to the df
for (i in 1:lenght(dates2){testdf[i, ] = c(dbGetQuery(con,paste0(' SELECT \
sdci_',year(dates2[i]),'_',sprintf("%02d",month(dates2[i])),'_mean from \ 
gr_sea_outlets_tier2 order by area_km2'))}

END OF EDIT

我使用此命令逐个获取数据:

data$"2000/8/1" = dbGetQuery(db,"SELECT sdci_2000_08_mean as '2000/08/01' from  gr_sea_outlets_tier2 order by area_km2 desc limit 1;")

但是因为我有50张桌子,所以这些过程变得有些无聊。

我试图为它创建一个循环,但我无法弄清楚语法。

这是我想要做的一些伪代码(像bash一样):

for year in $(seq 2000 2010); do
    for month in $(seq -w 05 09); do
         data$"$year"/"$month"/01" = dbGetQuery(db,"SELECT sdci_$year_$month_mean as '$year/$month/01' from  gr_sea_outlets_tier2 order by area_km2 desc limit 1;"); 
        done; 
 done

作为一个临时解决方案,我设法让bash为我创建一组命令来解析为R.

 for year in $(seq 2000 2010); do for month in $(seq -w 05 09); do echo data\$\'"$year"-"$month"-"01"\' \<\- dbConnect\(db,\"SELECT sdci_"$year"_"$month"_mean from gr_sea_outlets_tier2 order by area_km2 desc limit 1\;\"\) >> r.cmd.data ; done; done

但是我认为可以在R

中做到这一点

1 个答案:

答案 0 :(得分:1)

使用列表存储输出可能是最佳选择。但我们会让mapply为我们照顾。

# Get the inputs we want
years <- 2000:2010
months <- sprintf("%02d", 5:9)
dat <- expand.grid(months = months, years = years)

# Construct a function that gets the query given the month and year
getVal <- function(month, year){
    query <- paste0("SELECT sdci_", 
                    year, "_", month, "_mean as '", 
                    year, "/", month, 
                    "/01' from gr_sea_outlets_tier2 order by",
                    " area_km2 desc limit 1;")
    #dbGetQuery(db, query)
    query
}

# Actually apply the function to each month/year combo of interest
out <- mapply(getVal, dat$months, dat$years)

我注释了dbGetQuery调用,而只是返回了要进行的查询。您应该至少运行一次,以便在实际运行查询之前检查这些是您想要的查询。一旦您想要运行它们,只需取消注释dbGetQuery并删除仅包含查询的行。


编辑:如果我们真的想要一个基于for循环的解决方案,那么请使用此代替mapply

dat <- list()
for(month in months){
    for(year in years){
        id <- paste(year, month, 1, sep = "/")
        dat[[id]] <- getVal(month, year)
    }
}