1

In ggplot(), you can use a column name as a reference in aes():

p <- ggplot(mtcars, aes(wt, mpg))
p + geom_point()

I'm storing my column names as strings. Is it possible to switch a string to a column-name reference in R?

# This doesn't work
var1 = "wt"
var2 = "mpg"
p <- ggplot(mtcars, aes(var1, var2))
p + geom_point()
1
  • 3
    Just use aes_string instead of aes. Commented Feb 28, 2015 at 23:03

1 Answer 1

6

You can access the variables using the get() command, like this:

var1 = "wt"
var2 = "mpg"
p <- ggplot(data=mtcars, aes(get(var1), get(var2)))
p + geom_point()

which outputs: enter image description here

get is a way of calling an object using a character string. e.g.

e<-c(1,2,3,4)

print("e")
[1] "e"
print(get("e"))
[1] 1 2 3 4
print(e)
[1] 1 2 3 4

identical(e,get("e"))
[1] TRUE
identical("e",e)
[1] FALSE
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.