我是靠谱客的博主 鲤鱼黑夜,这篇文章主要介绍R语言:自定义函数,现在分享给大家,希望可以做个参考。

R语言系列:自定义function

在用R语言做各种事物时,用户自定义函数是不可或缺的。这期来讲讲如何自定义R的function。首先要介绍的是function的基本框架:

复制代码
1
2
3
4
myfunction <- function(arg1, arg2, ... ){ statements return(object) }
  • 函数名称为myfunction
  • arg1,arg2 为参数
  • statements 为函数语句
  • return(object)返回结果

两个例子

例子一:随机数产生,画图

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
function1 <- function(x,y){ plot(x,y) return(x+y) } > x <- rnorm(10) > y <- rnorm(10,2,3) > function1(x,y) [1] 1.5828019 0.2661017 -2.7666838 9.9395144 3.3619610 -0.9452065 -6.4638374 -0.3288615 1.1402272 [10] -0.1285368

出结果图

plot图

例子二:判断、条件句

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function2 <- function(x,npar=TRUE,print=TRUE) { if (!npar) { center <- mean(x); spread <- sd(x) } else { center <- median(x); spread <- mad(x) } if (print & !npar) { cat("Mean=", center, "n", "SD=", spread, "n") } else if (print & npar) { cat("Median=", center, "n", "MAD=", spread, "n") } result <- list(center=center,spread=spread) return(result) } > x<-rnorm(10,0,1) > function2(x) Median= 0.2469624 MAD= 1.161068 $center [1] 0.2469624 $spread [1] 1.161068

总结

看懂这两,基本的函数应该可以实现,稍微复杂的,或别的更加复杂的函数,那就需要经验了。多练习多写代码是实现快速写代码的重要途径!

最后

以上就是鲤鱼黑夜最近收集整理的关于R语言:自定义函数的全部内容,更多相关R语言内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(94)

评论列表共有 0 条评论

立即
投稿
返回
顶部