[R] attaching data.frame/list within a function
John Fox
jfox at mcmaster.ca
Wed Apr 14 20:31:14 CEST 2004
Dear Gardar,
You could use with(); to modify your example slightly,
> a <- "a"
> b <- 5
> foo <- function(x=0, input=list(a=10)) {
+ with(input, {
+ print(c(a, b, x))
+ })
+ }
> foo()
[1] 10 5 0
>
I hope that this helps,
John
> -----Original Message-----
> From: r-help-bounces at stat.math.ethz.ch
> [mailto:r-help-bounces at stat.math.ethz.ch] On Behalf Of Gardar
> Johannesson
> Sent: Wednesday, April 14, 2004 1:14 PM
> To: r-help at stat.math.ethz.ch
> Subject: [R] attaching data.frame/list within a function
>
> I'm trying to find a good way of attaching a list within a
> function such that the attached variables (the list's
> members) precede the global environment (.GlobalEnv) in the
> search list. Here is a non-working example using attach(),
> which hopefully explains better what I'm trying to do:
>
> > foo <- function(x=0, input=list(a=10)) {
> + attach(input)
> + on.exit(detach(input))
> + print(search())
> + print(a)
> + }
> >
> > a
> Error: Object "a" not found
> > foo() ## this prints out a = 10
> [1] ".GlobalEnv" "input" "package:methods"
> "package:stats"
> [5] "package:graphics" "package:utils" "Autoloads"
> "package:base"
> [1] 10
> >
> > a <- 0
> > foo() ## this prints out a = 0, not a = 10
> [1] ".GlobalEnv" "input" "package:methods"
> "package:stats"
> [5] "package:graphics" "package:utils" "Autoloads"
> "package:base"
> [1] 0
> >
>
>
> Thanks,
>
> Gardar
>
More information about the R-help
mailing list