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()
David Arenburg
  • 89,637
  • 17
  • 130
  • 188
user1582665
  • 121
  • 2
  • 11

1 Answers1

5

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
bjoseph
  • 2,046
  • 15
  • 23