**
教材P103 5.5 用户自编函数function()函数实例
**
- 代码清单5-8
#随机生成50个服从正态分布的样本数据,组成向量存储于x内,并计算出均值和标准差待后续验证。
> set.seed(1234) #
> x<- rnorm(50)
> x
[1] -1.20706575 0.27742924 1.08444118 -2.34569770 0.42912469
[6] 0.50605589 -0.57473996 -0.54663186 -0.56445200 -0.89003783
[11] -0.47719270 -0.99838644 -0.77625389 0.06445882 0.95949406
[16] -0.11028549 -0.51100951 -0.91119542 -0.83717168 2.41583518
[21] 0.13408822 -0.49068590 -0.44054787 0.45958944 -0.69372025
[26] -1.44820491 0.57475572 -1.02365572 -0.01513830 -0.93594860
[31] 1.10229755 -0.47559308 -0.70944004 -0.50125806 -1.62909347
[36] -1.16761926 -2.18003965 -1.34099319 -0.29429386 -0.46589754
[41] 1.44949627 -1.06864272 -0.85536463 -0.28062300 -0.99434008
[46] -0.96851432 -1.10731819 -1.25198589 -0.52382812 -0.49684996
> mean(x)
[1] -0.453053
> sd(x)
[1] 0.8850435
#用function功能定义mystats函数
> mystats<- function(x, parametric=TRUE, print=FALSE) #这里定义了parametric和print两个参数,前者默认为真,后者默认为假(注意:parametric和print只是两个随便取的名字,换成p1和p2也无所谓,不要被误导了)
> {
+ if (parametric) {
+ #如果parametric为真(即上一条定义的TRUE)
+ center<- mean(x);spread<- sd(x)
+ } else {
+ center <- median(x);spread<- mad(x)
+ }
+ if (print & parametric) {
+ #如果print和parametric都为真(但是print初始定义是FALSE不为真,所以这条if指令不予执行,跳到下一步else if再次判断,发现也不符合定义,故也不执行)
+ cat("mean=", center, "\n", "mad=", spread, "\n")
+ } else if (print & !parametric) {
+ cat("median=", center, "\n", "mad=", spread, "\n")
+ }
+ result<- list(center=center, spread=spread)
+ return(result)
+ }
> y<- mystats(x)
> y
$center
[1] -0.453053
$spread
[1] 0.8850435
#如果把上面的parametric和print初始值改一下,则判断条件后最终执行的是else if这段命令
> mystats<- function(x, parametric=FALSE, print=TRUE) {
+ if (parametric) {
+ center<- mean(x);spread<- sd(x)
+ } else {
+ center <- median(x);spread<- mad(x)
+ }
+ if (print & parametric) {
+ cat("mean=", center, "\n", "mad=", spread, "\n")
+ } else if (print & !parametric) {
+ cat("median=", center, "\n", "mad=", spread, "\n")
+ }
+ result<- list(center=center, spread=spread)
+ return(result)
+ }
>
> y
$center
[1] -0.53523
$spread
[1] 0.6836762
> y$center
[1] -0.53523
> mystats(x)$center
median= -0.53523
mad= 0.6836762
[1] -0.53523
> center
错误: 找不到对象'center'
#注意:center和spread都是基于mystats()这个函数定义的,并不独立于函数外存在,所以直接输入center或spread都是会报错的