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
  • 91,361
  • 17
  • 137
  • 196
colej1390
  • 157
  • 4
  • 11

1 Answers1

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
bjoseph
  • 2,116
  • 17
  • 24