R-教材P103 function函数实例

本文介绍了R语言中用户自编函数function的应用,通过代码清单5-8展示如何使用function生成50个正态分布样本数据,计算均值和标准差。同时探讨了function参数的改变如何影响判断和执行逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

**

教材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都是会报错的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值