1

I am trying to create a plot function to create scatter plots. However it cannot seem to work. I believe the df[,y] and df[,x] seems to be the problem but am not sure whats wrong. Please help!

class<-c(1,2,3,4) 
level<-c(1,2,3,4) 
school<-c(2,3,4,5)
score<-c(5,6,7,8)
performance<-c(3,7,6,5)
dataframe = data.frame(class,level,school,score,performance)

plotScatter <- function(x, y, df) {
  plot(df[,y]~df[,x])
}

plotScatter(score, performance, dataframe)
TYL
  • 1,577
  • 20
  • 33
  • 1
    Can also be done with `ggplot2` & tidy evaluation https://stackoverflow.com/a/50930640/786542 – Tung Nov 27 '18 at 07:27

1 Answers1

2

The problem does indeed originate from the way you subset df inside your plotScatter function. To plot the two columns against each other, in df[,x] the x is expected to be a string (and the same for df[,y]).

Here are two ways to solve it:

1) call the function with x and y as strings

plotScatter <- function(x, y, df) {
  plot(df[,y]~df[,x])
}
plotScatter('score', 'performance', dataframe)

2) use deparse and substitute inside the function to convert the variables to strings

plotScatter <- function(x, y, df) {
  x <- deparse(substitute(x))
  y <- deparse(substitute(y))
  plot(df[,y]~df[,x])
}
plotScatter(score, performance, dataframe)
bobbel
  • 1,983
  • 6
  • 21