Q:

Accessing Arbitrary Columns from an R Data Frame using with()

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 can use get:
with(df, get(column.name))

