tags:

views:

231

answers:

2

Suppose that I have a data frame with a column whose name is stored in a variable. Accessing this column using the variable is easy using bracket notation:

df <- data.frame(A = rep(1, 10), B = rep(2, 10))
column.name <- 'B'

df[,column.name]

But it is not obvious how to access an arbitrary column using a call to with(). The naive approach

with(df, column.name)

effectively evaluates column.name in the caller's environment. How can I delay evaluation sufficiently that with() will provide the same results that brackets give?

A: 

You use 'with' to create a localized and temporary namespace inside which you evaluate some expression. In your code above, you haven't passed in an expression.

For instance:

data(iris)   # this data is in your R installation, just call 'data' and pass it in

Ordinarily you have to refer to variable names within a data frame like this:

tx = tapply(iris$sepal.len, list(iris$species), mean)

Unless you do this:

attach(iris)

The problem with using 'attach' is the likelihood of namespace clashes, so you've got to remember to call 'detach'

It's much cleaner to use 'with':

tx = with( iris, tapply(sepal.len, list(species), mean) )

So, the call signature (informally) is: with( data, function() )

doug
That's a good summary of `with()`, but I'd like to know how to force the value of `column.name` to become the desired expression.
johnmyleswhite
+3  A: 

You can use get:

with(df, get(column.name))
Eduardo Leoni