r - 在 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)
解决方案
问题确实源于您df
在plotScatter
函数中设置子集的方式。为了将两列相互绘制, in预计是一个字符串(对于 也是如此df[,x]
)。x
df[,y]
这里有两种解决方法:
1) 使用 x 和 y 作为字符串调用函数
plotScatter <- function(x, y, df) {
plot(df[,y]~df[,x])
}
plotScatter('score', 'performance', dataframe)
2)在函数内部使用deparse
andsubstitute
将变量转换为字符串
plotScatter <- function(x, y, df) {
x <- deparse(substitute(x))
y <- deparse(substitute(y))
plot(df[,y]~df[,x])
}
plotScatter(score, performance, dataframe)
推荐阅读
- javascript - 基于另一个输入的最大日期
- javascript - Vue.js,Three.js,如何在动画循环中更改 CSS 样式元素
- css - 悬停项目,在项目文本的宽度下获得一个框
- google-cloud-platform - 云运行并保持活动标题
- go - golang结构链码行为中的json编码
- android - Android:底部弹出活动
- node.js - 在 TypeScript 中为 Azure 函数指定 VS Code launch.json runtimeVersion
- python - 将参数传递给类方法会导致 TypeError
- php - Post Loop 显示在一页上,但不在另一页上
- tensorflow - Skopt gp_minimize eroor 同时寻找最佳点