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

Posted by johnmyleswhite on Stack Overflow See other posts from Stack Overflow or by johnmyleswhite
Published on 2010-04-10T18:17:24Z Indexed on 2010/04/10 19:13 UTC
Read the original article Hit count: 161

Filed under:

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?

© Stack Overflow or respective owner

Related posts about r