Mark Leeds asked:
>i am using the apply function
>in the following manner where temp is a matrix.
>
>tempindex_apply(temp,2,function(x) which(x == boundthreshold))
>
>but Splus doesn't understand boundthreshold because it
>is a variable in the program but i guess once you
>declare a function inside apply, it doesn't consider
>the global variables. is there a way to explain to
>the apply function that boundthreshold is the
>variable in the program or a way to send it into the function ?
>I did a help on apply but it didn't have this type of example.
>thanks.
>
> mark
Variables defined within functions are not global.
The best solution is usually to pass additional arguments to
apply, using ... . Another solution is to use assign, to frame 1.
Here is draft text for help(apply); comments welcome:
# If apply() is called from another function, then variables
# defined within that function are local to the function,
# and are not available to apply().
#
# This example will fail because variables are not global,
# so the version of myTrim defined in in colTrimmedMean is not
# available inside apply:
x <- rmvnorm(300, d=5)
colTrimmedMeans <- function(x, myTrim){
f <- function(x) mean(x, trim = myTrim)
apply(x, 2, f)
}
colTrimmedMeans(x, .2)
#
# Recommended solution: pass additional argument to the function
# The function must take an additional argument, and pass that
# argument by name when calling apply:
colTrimmedMeans <- function(x, myTrim){
f <- function(x, myTrim) mean(x, trim = myTrim)
apply(x, 2, f, myTrim = myTrim)
}
colTrimmedMeans(x, .2)
#
# Another solution: save object on frame 1
# Warning, this may cause memory buildup if used repeatedly
colTrimmedMeans <- function(x, myTrim){
f <- function(x) mean(x, trim = myTrim)
assign("myTrim", myTrim, frame = 1)
apply(x, 2, f)
}
colTrimmedMeans(x, .2)
|