繁体   English   中英

在R中创建绘图函数

[英]Creating a plot function in 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)

问题的确确实源于您在plotScatter函数中对df子集化的方式。 为了将两列相对绘制,在df[,x]x应该是字符串(与df[,y] )。

有两种解决方法:

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM