Solution:
Combining the answer bellow:
#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
I am getting my data one-by-one with this command:
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;")
but since I have 50 tables the processes becomes a bit tiresome.
Im trying to create a loop for it but I can’t figure the syntax.
Here is some pseudocode (bash like) for what I want to do:
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
As a tempory solution ive manages to get bash to create a set of commands for me to parse into 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
But Ι think its possible to do it inside R
Using a list to store the output would probably be the best option. But we’ll let
mapplytake care of that for us.I commented out the
dbGetQuerycall and instead just returned the query to be made. You should probably run it at least once like this to check that those are the queries you want before actually running the queries. Once you want to run them just uncomment the call todbGetQueryand delete the line that just contains query.Edit: If we really want a
forloop based solution then use this instead ofmapply: