【问题标题】:Outputting R syntax from within a function从函数中输出 R 语法
【发布时间】:2018-01-18 18:02:35
【问题描述】:

我正在教授一门统计课程,我试图轻轻地向我的学生介绍 R 语法(特别是 ggplot)。为此,我为许多基本命令创建了包装函数。例如:

basic.plot.function = function(x,y, data=d){
    p = ggplot(data, aes_string(x=x, y=y)) + geom_point() + geom_smooth()
    print(p)
    #dput(p) # this function isn't doing what I want it to
}

我希望函数输出绘图(这是 print(p) 所做的),但我也希望它向控制台写入用于创建它的实际代码。换句话说,如果用户输入:

mydata = data.frame(x1 = runif(100), x2 = runif(100))
basic.plot.function("x1","x2", data=mydata)

我希望它输出:

ggplot(mydata, aes_string(x="x1", y="x2")) + geom_point() + geom_smooth()

有什么想法可以做到吗?

【问题讨论】:

    标签: r string function output


    【解决方案1】:

    解决方案

    library(ggplot2)
    basic.plot.function = function(x, y, data = d){
        call <- paste0('ggplot(', deparse(substitute(data)), ', aes_string(x=',
                       deparse(substitute(x)), ', y=', deparse(substitute(y)),
                       ')) + geom_point() + geom_smooth()')
        p <- eval(parse(text = call))
        print(p)
        print(call)
    }
    

    示例

    data("iris")
    basic.plot.function('Sepal.Length', 'Sepal.Width', iris)
    
    > basic.plot.function('Sepal.Length', 'Sepal.Width', iris)
    `geom_smooth()` using method = 'loess'
    [1] "ggplot(iris, aes_string(x=\"Sepal.Length\", y=\"Sepal.Width\")) + geom_point() + geom_smooth()"
    

    说明

    desparse(substitute(x)) 将参数x 转换为字符串。在打印 ggplot 对象时,您可以使用它来制作要打印的函数调用字符串。您可以使用 eval(parse()) 评估该字符串以创建您的 ggplot 对象。

    【讨论】:

      猜你喜欢
      • 2021-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-03
      • 2019-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多