【R语言学习笔记】8、R用户自定义函数

用户函数自定义

  • 格式:
myfunction <- function(arg1, arg2, ... ){
	statements
	return(object)
}

其中:函数名称为myfunction
arg1arg2 为参数
statements 为函数语句
return(object)返回结果

  • 例子
> mydate <- function(type){
+ switch(type,
+ long = format(Sys.time(), "%A %B %d %Y"),
+ short = format(Sys.time(), "%m-%d-%y"),
+ cat(type, "is not recognized type\n"))}
> mydate("long")
[1] "星期日 八月 18 2019"
> mydate("short")
[1] "08-18-19"
> mydate("medium")
medium is not recognized type

for循环在函数中的使用

  • 例子,计算minnum-maxnum之间的数字的累加。
> sum <- function(minnum,maxnum){
+ x <- 0
+ for (i in minnum:maxnum){
+ x <- x + i
+ }
+ return(x)
+ }
> sum(2,4)
[1] 9

注: 若想修改函数,则执行fix(函数名)就会弹出该函数的编辑器窗口,即可进行对其进行修改。

发布了44 篇原创文章 · 获赞 5 · 访问量 4493

猜你喜欢

转载自blog.csdn.net/ljb0077/article/details/99704543