1

ldplyデータベースを複数回クエリすることを目的としたRスクリプトを作成しています(3つのベクトルの要素からの順列ごとに1つですが、これを達成するために使用する方法を理解するのに苦労しています .

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)

ldply ネストされた ldply を各ベクトルに 1 つずつ、3 回使用できると思っていましたが、最初のレベルから抜け出すことさえできません。

私にできることはありますか?

4

2 に答える 2

3

mdplyを使用すると(または同等に) 、これはかなり単純化されると思いますmapply

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(tags, times, timesteps) {

  sql <- paste("select tag, time, timestep, value from mydb where 
            tag = '",tags,"' and time = '",times,"' and timestep = '",timesteps,"'", sep="")
  # pretend the line below is actually querying a database and returning a DF with one row
  data.frame(tag = tags, time = times, timestep = timesteps, value = rnorm(1))

}

dat <- expand.grid(tags, times, timesteps)
colnames(dat) <- c('tags','times','timesteps')

mdply(dat,query)

データと関数の引数全体で変数名がすべて一致するように、変数名がわずかに変更されていることに注意してください。

于 2012-08-08T15:00:24.550 に答える
1

これで仕事は完了しますが、適用のみを使用します。まず、対象の組み合わせでオブジェクトを作成し、次にクエリを書き直して、3 つの入力ではなくそのオブジェクトから行を取得します。

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")

# Use expand.grid to create an object with all the combinations
dat <- expand.grid(tags, times, timesteps)

# Rewrite query to take in a row of dat
query <- function(row) {
    # extract the pieces of interest
    tag <- row[1]
    time <- row[2]
    timestep <- row[3]

    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 on a single row  
query(dat[1,])

# apply the function to each row
j <- apply(dat, 1, query)
# bind all the output together
do.call(rbind, j)
于 2012-08-08T14:48:50.493 に答える