Re: [R] objects and environments

From: Gabor Grothendieck <ggrothendieck_at_gmail.com>
Date: Thu 10 Aug 2006 - 02:14:31 EST

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@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@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.
>



R-help@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. Received on Thu Aug 10 02:20:03 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Thu 10 Aug 2006 - 04:20:01 EST.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.