解决方案:
结合下面的答案:
#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'))}
编辑结束
我用这个命令一个接一个地获取我的数据:
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 中做到这一点