1

Here is the code on it's own that works.

ggplot(stkPres, aes(x = AAPL, y = AAPL.ret)) + geom_point()

Here is my attempt at a function:

graphic.stock.vs.return <- function(abbrev) {
  ggplot(stkPres, aes(x = abbrev, y = abbrev.ret)) + geom_point()
 
}

graphic.stock.vs.return(AAPL) would graph the exact same way as ggplot(stkPres, aes(x = AAPL, y = AAPL.ret)) + geom_point().

What do I need to do to my function for it to work properly?

mk2080
  • 872
  • 1
  • 8
  • 21
  • 1
    Please provide a full example including test input. See instructions at the top of the [tag:r] tag home page. – G. Grothendieck Jan 20 '21 at 23:24
  • 1
    I'm guessing you're looking for `aes_string(x = abbrev, y = paste0(abbrev, ".ret"))`. – teunbrand Jan 21 '21 at 00:23
  • These might be helpful https://stackoverflow.com/questions/22309285/how-to-use-a-variable-to-specify-column-name-in-ggplot/55524126#55524126 & https://stackoverflow.com/questions/4856849/looping-over-variables-in-ggplot/52045613#52045613 – Tung Jan 21 '21 at 00:57

1 Answers1

0

If you are going to pass value in an unquoted way you could do :

library(ggplot2)

graphic.stock.vs.return <- function(abbrev) {

  abbr <- deparse(substitute(abbrev))
  ggplot(stkPres, aes(x = .data[[abbr]],
                      y = .data[[paste0(abbr, '.ret')]])) + geom_point()
}

graphic.stock.vs.return(AAPL) 

If you are going to pass variable as string.

graphic.stock.vs.return <- function(abbr) {
  ggplot(stkPres, aes(x = .data[[abbr]], 
                      y = .data[[paste0(abbr, '.ret')]])) + geom_point()
}

graphic.stock.vs.return("AAPL") 
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213