[R] objects and environments
Gabor Grothendieck
ggrothendieck at gmail.com
Wed Aug 9 18:14:31 CEST 2006
Dmitris has already provided the solution but just throught I would'
mention that your third alternative can be written:
apply(mymatrix, 1, fun2, bb = bb)
(assuming fun2 has arguments idx and bb) which is not
nearly so ugly so you might reconsider whether its ok
for you to just pass bb.
On 8/9/06, Adrian Dusa <dusa.adrian at gmail.com> wrote:
> Dear list,
>
> I have two functions created in the same environment, fun1 and fun2.
> fun2 is called by fun1, but fun2 should use an object which is created in fun1
>
> fun1 <- function(x) {
> ifelse(somecondition, bb <- "o", bb <- "*")
> ## mymatrix is created, then
> myresult <- apply(mymatrix, 1, fun2)
> }
>
> fun2 <- function(idx) {
> if (bb == "o) {
> # do something with idx
> } else {
> # do something else with idx
> }
> }
>
> What should I do to have "bb" available in fun2?
> I tried everything I could with sys.parent(), sys.frame(), parent.env() but it
> just doesn't want to work.
>
> I have three solutions but none of them satisfactory; inside fun1:
> 1. assign("bb", aa, .GlobalEnv) # don't want to do that, do I?
> 2. assign("bb", aa, 1) # for some reason "aa" appears in the .GlobalEnv anyway
> 3. pass "bb" as an argument to fun2, but this would require:
> apply(mymatrix, 1, function(idx) fun2(idx, bb)) # which is not elegant
>
>
> I played further with assign and get, but there's something I'm missing:
>
> fun1 <- function() {
> e2 <- new.env()
> assign("bb", 4, e2)
> fun2()
> }
>
> fun2 <- function(idx) {
> get("bb", e2)
> }
>
> > fun1()
> Error in get("bb", e2) : object "e2" not found
>
> Any hint would be highly appreciated,
> Adrian
>
> --
> Adrian Dusa
> Romanian Social Data Archive
> 1, Schitu Magureanu Bd
> 050025 Bucharest sector 5
> Romania
> Tel./Fax: +40 21 3126618 \
> +40 21 3120210 / int.101
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
More information about the R-help
mailing list