【问题标题】:Difference between "direct code" and making a certain "function" in R codeR代码中“直接代码”与制作某个“功能”的区别
【发布时间】:2017-05-09 15:55:18
【问题描述】:

我正在疯狂地混淆我的工作。

代码中的细节并不重要,我有两种选择

第一个:

 ggplot(dta_fin, aes(x=PVT_0610_Z, y=PVT_1115_Z)) +
      geom_point(shape=1) +
      geom_vline(xintercept = 0, linetype="dashed") +
      geom_hline(yintercept = 0, linetype="dashed") +
      geom_smooth(method='lm') +
      facet_wrap(~ GROUP, scales="fixed", ncol=3)      

R中函数使用的第二个:

aFunction <-function(dataname,xx,yy)
      {
        ggplot(dataname, aes(x=xx, y=yy)) +
          geom_point(shape=1) +
          geom_vline(xintercept = 0, linetype="dashed") +
          geom_hline(yintercept = 0, linetype="dashed") +
          geom_smooth(method='lm') +
          facet_wrap(~ GROUP, scales="fixed", ncol=3)
      }

      aFunction(dta_fin,PVT_0610_Z,PVT_1115_Z)

从第一个和第二个得到相同的图形是很自然的,但是我从两个代码中得到不同的图形。是什么原因??............

【问题讨论】:

  • 您能否提供一些数据和一个最小示例,以便我们重现您的问题?
  • 在函数内部使用aes_string,并使用字符串而不是裸名来传递列名

标签: r function ggplot2


【解决方案1】:

从函数内部调用 ggplot 时应该使用 aes_string():

aFunction <-function(dataname,xx,yy)
      {
        ggplot(dataname, aes_string(x=xx, y=yy)) +
          geom_point(shape=1) +
          geom_vline(xintercept = 0, linetype="dashed") +
          geom_hline(yintercept = 0, linetype="dashed") +
          geom_smooth(method='lm') +
          facet_wrap(~ GROUP, scales="fixed", ncol=3)
      }

不要忘记将 xx 和 yy 作为字符串传递给里面的函数:

  aFunction(dta_fin,PVT_0610_Z,PVT_1115_Z)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-29
    • 1970-01-01
    • 2017-09-23
    • 2012-09-27
    • 1970-01-01
    相关资源
    最近更新 更多