分配函数及其';将条件转换为变量,以便稍后在script-R中使用

分配函数及其';将条件转换为变量,以便稍后在script-R中使用,r,variable-assignment,R,Variable Assignment,因此,我有一个函数,我想在脚本中的多个位置使用它,但我不想一遍又一遍地重复脚本部分。我可以把它赋给这样的变量吗 png(filename = "comparison_plot.png", units = "px", width = 1920, height = 1080, res = 150, bg = "white", type = "cairo") function <- png(filename = "comparison_plot.png",

因此,我有一个函数,我想在脚本中的多个位置使用它,但我不想一遍又一遍地重复脚本部分。我可以把它赋给这样的变量吗

  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")
它将调用函数并执行我编写的操作:

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

谢谢大家!

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

make_comparison_plot = function(){
 png(filename = "comparison_plot.png",
  units = "px",
  width = 1920,
  height = 1080,
  res = 150,
  bg = "white",
  type = "cairo")
}
然后执行
make\u comparison\u plot()
并执行函数体中的内容

一些注意事项:

  • 不要调用你的函数<;代码>;>;>;>;>;>;>;>;>;>;>;>;>;>;>;>;>;>;>;>;>;>;>;>
  • 您可以创建一个简单的单词,如
    make\u comparison\u plot
    do thing,但最好创建一个函数并使用
    make\u comparison\u plot()
    (即带括号)调用它
  • 所以你写了一个函数,它只做一件事。您可能希望对其进行更改,因此更好的做法是将参数作为默认值
例如:


然后
make\u comparison\u test()
将像以前一样工作,但您也可以尝试
make\u comparison\u test(filename=“compare2.png”)
并获得不同的输出文件。或者
进行比较测试(filename=“small.png”,width=100,height=100)
。这就是编写函数的能力。

然后编写一个函数来执行以下操作:

make_comparison_plot = function(){
 png(filename = "comparison_plot.png",
  units = "px",
  width = 1920,
  height = 1080,
  res = 150,
  bg = "white",
  type = "cairo")
}
然后执行
make\u comparison\u plot()
并执行函数体中的内容

一些注意事项:

  • 不要调用你的函数<;代码>;>;>;>;>;>;>;>;>;>;>;>;>;>;>;>;>;>;>;>;>;>;>;>
  • 您可以创建一个简单的单词,如
    make\u comparison\u plot
    do thing,但最好创建一个函数并使用
    make\u comparison\u plot()
    (即带括号)调用它
  • 所以你写了一个函数,它只做一件事。您可能希望对其进行更改,因此更好的做法是将参数作为默认值
例如:


然后
make\u comparison\u test()
将像以前一样工作,但您也可以尝试
make\u comparison\u test(filename=“compare2.png”)
并获得不同的输出文件。或者
进行比较测试(filename=“small.png”,width=100,height=100)
。这就是写函数的能力。

你就快到了。如果不更改函数中的参数,可以创建一个参数列表为空的函数。因此,您的代码看起来像:
myfun您就快到了。如果不更改函数中的参数,可以创建一个参数列表为空的函数。因此,您的代码看起来像:
myfun,非常有效!!谢谢同时也感谢你的建议,默认的东西在我的脚本中会非常有用。这非常有效!!谢谢也谢谢你的建议,默认的东西在我的脚本中非常有用。
  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)
  }