【问题标题】:Assign function and it's conditions to a variable for use later in script - R将函数及其条件分配给一个变量,以便稍后在脚本中使用 - R
【发布时间】:2017-11-29 10:54:57
【问题描述】:

所以我想在脚本的多个位置使用一个函数,但我不想一遍又一遍地重复脚本部分。我可以将它分配给这样的变量吗?

  png(filename = "comparison_plot.png",
  units = "px",
  width = 1920,
  height = 1080,
  res = 150,
  bg = "white",
  type = "cairo")

  function <- png(filename = "comparison_plot.png",
                  units = "px",
                  width = 1920,
                  height = 1080,
                  res = 150,
                  bg = "white",
                  type = "cairo")

然后当我稍后在脚本中使用它时:

>function

它将调用该函数并执行我编写的代码:

  png(filename = "comparison_plot.png",
  units = "px",
  width = 1920,
  height = 1080,
  res = 150,
  bg = "white",
  type = "cairo")

谢谢大家!

【问题讨论】:

  • 你快到了。如果您不更改函数中的参数,您可以创建一个带有空参数列表的函数。因此,您的代码将如下所示:myfun &lt;- function() {mycode}.

标签: r variable-assignment


【解决方案1】:

然后编写一个执行此操作的函数:

make_comparison_plot = function(){
 png(filename = "comparison_plot.png",
  units = "px",
  width = 1920,
  height = 1080,
  res = 150,
  bg = "white",
  type = "cairo")
}

然后您执行make_comparison_plot(),它会在函数的body 中执行这些操作。

一些注意事项:

  • 不要调用你的函数function - 它不是描述性的,它也是用于定义函数的 R 关键字。
  • 可以做一个像make_comparison_plot 这样的简单词做事,但最好创建一个函数并用make_comparison_plot() 调用它(即用括号)。
  • 所以您已经编写了一个只做一件事的函数。您可能希望对此进行更改,因此最好将参数设置为默认值。

例如:

  make_comparison_plot = function(filename = "comparison_plot.png",
        units = "px",
        width = 1920,
        height = 1080,
        res = 150,
        bg = "white",
       type = "cairo"){
   png(filename=filename, units=units, width=width, height=height, res=res, bg=bg, type=type)
  }

然后make_comparison_test() 将像以前一样工作,但您也可以尝试make_comparison_test(filename="compare2.png") 并获得不同的输出文件。或make_comparison_test(filename="small.png", width=100, height=100)。这就是编写函数的力量。

【讨论】:

  • 效果很好!!谢谢!也感谢您的建议,默认设置在我的脚本中将非常有用。
猜你喜欢
  • 2021-02-14
  • 2013-10-13
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
  • 2019-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多