将函数及其条件分配给一个变量,以便稍后在脚本中使用 - R
Assign function and it's conditions to a variable for use later in script - R
所以我有一个函数想在我的脚本中的多个地方使用,但我不想一遍又一遍地重复脚本部分。我可以将它分配给这样的变量吗?
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")
谢谢大家!
然后编写一个函数来执行此操作:
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)
。这就是写函数的力量。
所以我有一个函数想在我的脚本中的多个地方使用,但我不想一遍又一遍地重复脚本部分。我可以将它分配给这样的变量吗?
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")
谢谢大家!
然后编写一个函数来执行此操作:
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)
。这就是写函数的力量。