将不同的列传递给函数内的aes [英] passing varying columns to aes inside a function

查看:87
本文介绍了将不同的列传递给函数内的aes的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  hmean<  -  function()这个函数可以调用ggplot,数据,列,标签=标签){
ggplot(data,aes(column))+
geom_histogram()+
facet_wrap(〜Antibody,ncol = 2)+
ggtitle (粘贴(平均抗体计数(Log2)for,标签,stain))
}
hmean(Log2Means,Primary.Mean,Label =Primary)
eval (expr,envir,enclos):找不到对象'column'

主要.Mean 是不同的参数(我有多种方式)。在这里的各种帖子之后,我尝试过把


  1. 传递给列名引用和未引用(其中称为意外字符串常量或对象找不到错误)
  2. 设置本地环境( foo <-environment(),后面跟着一个使用 data2 $列< - data [,column
  3. 创建数据集的新副本) ]

这些在ggplot中看起来都不起作用。 b $ b我会用不同的data.frames和columns来调用它:

  hmean(Log2Means,Primary.mean,Label = Primary)
hmean(Log2Means,Secondary.mean,Label =Secondary)
hmean(SomeOtherFrame,SomeColumn,Label =Pretty Label)


解决方案

您的示例不是重可以这样做:

  hmean<  -  function(data,column,Label = label) {
ggplot(data,do.call(aes,list(y = substitute(column))))+
geom_histogram()+
facet_wrap(〜Antibody,ncol = 2) +
ggtitle(paste(Mean Antibody Counts(Log2)for,Label,stain))
}

hmean(Log2Means,Primary.Mean,Label =主要)

如果您需要更多参数给 aes

  do.call(aes,list(y = substitute(function_parameter),x = quote(literal_parameter)))


I am trying to write a function that calls ggplot with varying arguments to the aes:

hmean <- function(data, column, Label=label){
  ggplot(data,aes(column)) +
    geom_histogram() +
    facet_wrap(~Antibody,ncol=2) +
    ggtitle(paste("Mean Antibody Counts (Log2) for ",Label," stain"))
}
hmean(Log2Means,Primary.Mean, Label="Primary")
Error in eval(expr, envir, enclos) : object 'column' not found

Primary.Mean is the varying argument (I have multiple means). Following various posts here I have tried

  1. passing the column name quoted and unquoted (which yieds either an "unexpected string constant" or the "object not found error)
  2. setting up a local ennvironment (foo <-environment() followed by a environment= arg in ggplot)
  3. creating a new copy of the data set using a data2$column <- data[,column]

None of these appear to work within ggplot. How do I write a function that works? I will be calling it with different data.frames and columns:

hmean(Log2Means, Primary.mean, Label="Primary")
hmean(Log2Means, Secondary.mean, Label="Secondary")
hmean(SomeOtherFrame, SomeColumn, Label="Pretty Label")

You example is not reproducible, but likely this will work:

hmean <- function(data, column, Label=label){
    ggplot(data, do.call("aes", list(y = substitute(column))) ) +
        geom_histogram() +
        facet_wrap(~Antibody,ncol=2) +
        ggtitle(paste("Mean Antibody Counts (Log2) for ",Label," stain"))
}

hmean(Log2Means,Primary.Mean, Label="Primary")

If you need more arguments to aes, do like this:

do.call("aes", list(y = substitute(function_parameter), x = quote(literal_parameter)))

这篇关于将不同的列传递给函数内的aes的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆