首页 > 解决方案 > 在 r 中创建绘图函数

问题描述

我正在尝试创建一个绘图函数来创建散点图。但是,它似乎无法正常工作。我相信 df[,y] 和 df[,x] 似乎是问题所在,但不确定出了什么问题。请帮忙!

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)

标签: rfunctionplot

解决方案


问题确实源于您dfplotScatter函数中设置子集的方式。为了将两列相互绘制, in预计是一个字符串(对于 也是如此df[,x])。xdf[,y]

这里有两种解决方法:

1) 使用 x 和 y 作为字符串调用函数

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

2)在函数内部使用deparseandsubstitute将变量转换为字符串

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

推荐阅读