首页 文章

在R函数中使用ggplot2

提问于
浏览
0

我想写一个 R 函数读取文件 m ,并使用 ggplots2 绘制一个箱线图 .

这是功能:

stringplotter = function(m, n) {
library(ggplot2)
require(scales)
data<-as.data.frame(read.table(file=m, header=T, dec=".", sep="\t"))
ggplot(data, aes(x=string, y=n)) + geom_boxplot() + geom_point() + scale_y_continuous(labels=comma)
}

示例文件 test

C   string
97  ccc
95.2    ccc
88.6    nnn
0.5 aaa
86.4    nnn
0   ccc
85  nnn
73.9    nnn
87.9    ccc
71.7    nnn
94  aaa
76.6    ccc
44.4    ccc
92  aaa
91.2    ccc

当我然后调用该函数

stringplotter("test", C)

我收到了错误

Fehler: Column `y` must be a 1d atomic vector or a list
Call `rlang::last_error()` to see a backtrace

当我直接调用函数内部的命令时,一切都按预期工作 . 我的错误在哪里?

1 回答

  • 2

    问题是当你写 y = n 时, ggplot2 不知道如何评估 n 的值 . 您可以使用 rlang 来引用输入,并在输入的数据框中对其进行评估 -

    stringplotter <- function(m, n) {
      library(ggplot2)
      require(scales)
      data <-
        as.data.frame(read.table(
          file = m,
          header = T,
          dec = ".",
          sep = "\t"
        ))
      ggplot(data, aes(x = string, y = !!rlang::enquo(n))) + 
        geom_boxplot() + 
        geom_point() + 
        scale_y_continuous(labels = comma)
    }
    

相关问题