开发者

Need to access variables from a parent apply within a child apply without globally scoping

Let me try this again, I'm going to leave out the exact data/example and just walk through what I need to accomplish.

I need to apply a function over the rows of a data.frame, that is easy. Then I need to derive some variables within that function using the data.frame that was passed to it. Finally, I'd like to apply a ne开发者_C百科w function over a subset of the data.frame and use the derived variables in the new function.

Can someone please tell me the best practice way to do this rather than globally scoping each of my variables (var1, var2)?

cpt <- a.data.frame

query.db <- function(another.data.frame){
        var1 <- some.values
        var2 <- some.other.values
        apply(cpt[var1,], 1, calc.enrichment) #calc.enrichment needs to access var1, var2!
}

I tried writing the calc.enrichment function as a user-defined function rather than outside of the scope, but my list of arguments (var1, var2) weren't being recognized. Thanks for any help.


This silly example works for me and seems to address what you are after. We use var1 to index into the columns of the data.frame used in the apply function as you did. var2 is just the standard deviation of the first column of the data.frame passed to it. I'm guessing your real example does something a tad bit more useful.

cpt <- data.frame(a = rnorm(5), b = rnorm(5), c = rnorm(5))
another.data.frame <- data.frame(d = rnorm(5), e = rnorm(5), f = rnorm(5))

query.db <- function(dat, outer.dat) {
  var1 <- sample(1:nrow(dat), sample(1:nrow(dat), 1, FALSE), FALSE)
  var2 <- sd(dat[, 1])

  apply(outer.dat[var1 ,], 1, function(x) apples = x * sin(var2) / cos(var2) ^ 2)

}


query.db(another.data.frame, cpt)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜