R函数内ggplot2的用法

时间:2018-12-09 15:16:08

标签: r function ggplot2

我想编写一个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 个答案:

答案 0 :(得分: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)
}