Wakan Tanka
Wakan Tanka

Reputation: 8052

get column name from variable in with function

I can use with function following way:

with(mtcars, sum(mpg))
# [1] 642.9

Is it possible to load column name from variable? I've tried following with no luck:

column <- "mpg"
with(mtcars, sum(column))
# Error in sum(column) : invalid 'type' (character) of argument
with(mtcars, sum(eval(column)))
# Error in sum(eval(column)) : invalid 'type' (character) of argument

Upvotes: 0

Views: 68

Answers (1)

akrun
akrun

Reputation: 887501

There are couple of options. Either we use eval with as.name/as.symbol

with(mtcars, sum(eval(as.name(column))))
#[1] 642.9

Or we can use get

with(mtcars, sum(get(column)))
#[1] 642.9

Upvotes: 3

Related Questions