Skip to Content

How to use ldply over the permutations of several vectors?

I'm building an R script that's intended to query a database multiple times (one for every permutation from the elements of 3 vectors, but I'm having a hard time figuring out how to use ldply to achieve this.

tags <- c("tag1","tag2","tag3")
times <- c("2012-08-01 13:00:00","2012-08-07 21:00:00")
timesteps <- c("2m", "10m","60m", "90m")
query <- function(tag, time, timestep) {
  sql <- paste("select tag, time, timestep, value from mydb where tag = '",tag,"' and time = '",time,"' and timestep = '",timestep,"'", sep="")
  # pretend the line below is actually querying a database and returning a DF with one row
  data.frame(tag = tag, time = time, timestep = timestep, value = rnorm(1))
# function works correctly!  
query(time = times[1], tag = tags[1], timestep = timesteps[1])
# causes an error! (Error in FUN(X[[1L]], ...) : unused argument(s) (X[[1]]))
ldply(times, query, time = times, tag = tags, timestep = timesteps)

I thought I could use ldply nested three times, one for each vector, but I don't even get out of the first level!

Any ideas what I can do?