Reputation: 1637
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)
Upvotes: 1
Views: 2215
Reputation: 2031
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)
Upvotes: 2