help with environments

Previous Topic Next Topic
classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view

help with environments

Joshua Wiley-2
Dear list,

Although I tried to make a simple example, this may be too
lengthy/unclear of a question for anyone to want to provide an answer.

I have been trying to write two functions.  My goal is to have an
outer function ("foo") that will do some computations based on data
created by the nested function ("f").  In particular I want to:

1) create a new data frame using the data from users data, when specified
2) replace user's variable names with standard names (particularly the
argument names)
3) when the user does not specify an argument, possibly use defaults

to do this, I have been trying to pass the results of
(with some modifications if an argument was not specified), to eval()
using the user specified data.  Evidently, I do not have a very
thorough understanding of environments in R and have met with a
spectacular variety of failures.  II am also open to suggestions of
alternate ways to do this, from my rut I do not see any other elegant

As always, insight, suggestions, or recommended readings are greatly


f <- function(x, y) {
  d <- as.vector([-1L], "list")
  if (missing(y)) d$y <- 1
  output <-

foo <- function(data, value) {eval(substitute(value), data)}

mydf <- data.frame(var1 = 1:10, var2 = letters[1:10])

#### desired use
foo(data = mydf, value = f(var1))
#### desired output
    x y
1   1 1
2   2 1
3   3 1
4   4 1
5   5 1
6   6 1
7   7 1
8   8 1
9   9 1
10 10 1

#### Actual output
#Error in data.frame(x = var1, y = 1, check.names = TRUE,
#  stringsAsFactors = TRUE) :
#object 'var1' not found

## It has the right names.  This works:
eval(substitute(data.frame(x = var1, y = 1)), mydf)
## it is like I am one environment too nested

Joshua Wiley
Ph.D. Student, Health Psychology
University of California, Los Angeles

[hidden email] mailing list
PLEASE do read the posting guide
and provide commented, minimal, self-contained, reproducible code.