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)
1

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.