【问题标题】:Usage of ggplot2 inside R functionR函数中ggplot2的使用
【发布时间】:2018-12-09 15:16:08
【问题描述】:

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

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

【问题讨论】:

标签: r function ggplot2


【解决方案1】:

问题是当你写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)
}

【讨论】:

    猜你喜欢
    • 2020-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-05
    • 2018-09-19
    • 1970-01-01
    相关资源
    最近更新 更多