Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将dataframe列作为参数传递给用户定义的函数?_R - Fatal编程技术网

如何将dataframe列作为参数传递给用户定义的函数?

如何将dataframe列作为参数传递给用户定义的函数?,r,R,我要做的是为一个类设置一个基本的用户定义函数,它将为预测变量和目标变量创建一个箱线图。这是我的代码: ggplot(data=df, aes(x=target, y=predictor)) + geom_boxplot( aes(col=target), notch=TRUE)} #Below is how I'm calling the function BoxplotPredictorOnTarget(df$target, df$predictor) 我的问题是,有没有一种更优雅的

我要做的是为一个类设置一个基本的用户定义函数,它将为预测变量和目标变量创建一个箱线图。这是我的代码:

  ggplot(data=df, aes(x=target, y=predictor)) + geom_boxplot(
  aes(col=target), notch=TRUE)}
#Below is how I'm calling the function
BoxplotPredictorOnTarget(df$target, df$predictor)

我的问题是,有没有一种更优雅的方法可以在调用函数时使用dataframe列名作为参数?如果能够基于相同的参数将名称添加到生成的箱线图的x轴和y轴上,那就太好了。我也不知道这是怎么回事。当我调用函数并将列名放在双引号中,而不使用dataframe变量名和“$”运算符时,它返回一个方框图,该方框图只是一条直线,轴没有任何意义,它们只是列名。我很困惑为什么使用列名的字符串作为参数不起作用,当它们被插入函数时,它应该与我只写列名相同,对吗?

我们可以将列名字符串转换为符号并进行计算

library(ggplot2)  
BoxplotPredictorOnTarget <- function(df, target, predictor) {

    ggplot(data = df, aes(x= !! rlang::ensym(target),
              y= !! rlang::ensym(predictor))) +
         geom_boxplot(aes(col= !! rlang::ensym(target)), notch=TRUE)
   }

使用可复制的示例

data(iris)
BoxplotPredictorOnTarget(iris, 'Species', 'Sepal.Length')
-输出


我们可以将列名字符串转换为符号并计算

library(ggplot2)  
BoxplotPredictorOnTarget <- function(df, target, predictor) {

    ggplot(data = df, aes(x= !! rlang::ensym(target),
              y= !! rlang::ensym(predictor))) +
         geom_boxplot(aes(col= !! rlang::ensym(target)), notch=TRUE)
   }

使用可复制的示例

data(iris)
BoxplotPredictorOnTarget(iris, 'Species', 'Sepal.Length')
-输出