Reputation: 8052
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
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