R-5_程序设计课件.ppt

  1. 1、本文档共54页,可阅读全部内容。
  2. 2、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
  3. 3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载
  4. 4、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
R-5_程序设计课件

第五讲 R的数据结构(三) 程序设计;程序控制结构 ;分支结构 ;例如,如果变量lambda为缺失值就给它赋一个缺省值,可用: if(is.na(lambda)) lambda - 0.5; 又比如要计算向量x的重对数,这只有在元素都为正且对数都为正时才能做到,因此需要先检查:if (all(x0) all(log(x) 0)) { y - log(log(x)); print(cbind(x,y)); } else { cat(Unable to comply\n); } 注意“”表示“与”,它是一个短路运算符,即第一个条件为假时就不计算第二个条件。如果不这样此例中计算对数就可以有无效值。 在条件中也可以用“||”(两个连续的竖线符号)表示“或”,它也是短路运算符,当第一个条件为真时就不再计算第二个条件。 “” 、“||”只对标量适用,而“” 、“|”适用于向量;在用R编程序时一定要时刻牢记R是一个向量语言,几乎所有操作都是对向量进行的。而R中的if语句却是一个少见的例外,它的判断条件是标量的真值或假值。比如,我们要定义一个分段函数f(x),当x为正时返回1,否则返回0,马上可以想到用if语句实现如下: if(x0) 1 else 0 当x是标量时这个定义是有效的,但是当自变量x是一个向量时,比较的结果也是一个向量,这时条件无法使用。所以,这个分段函数应该这样编程: y= numeric(length(x)) y[x0] - 1 y[x=0] - 0 有多个if语句时else与最近的一个配对。可以使用if ... else if ... else if ... else ...的多重判断结构表示多分支。多分支也可以使用switch()函数。;help(swicth) switch(base) Select One of a List of Alternatives Description switch evaluates EXPR and accordingly chooses one of the further arguments (in ...). Usage switch(EXPR, ...) Arguments EXPRan expression evaluating to a number or a character string....the list of alternatives, given explicitly. Details If the value of EXPR is an integer between 1 and nargs()-1 then the corresponding element of ... is evaluated and the result returned. If EXPR returns a character string then that string is used to match the names of the elements in .... If there is an exact match then that element is evaluated and returned if there is one, otherwise the next element is chosen, e.g., switch(cc, a=1, cc=, d=2) evaluates to 2. In the case of no match, if theres a further argument in switch that one is returned, otherwise NULL. See Examples;Examples require(stats) centre - function(x, type) { switch(type, mean = mean(x), median = median(x), trimmed = mean(x, trim = .1)) } x - rcauchy(10) centre(x, mean) centre(x, median) centre(x, trimmed) ccc - c(b,QQ,a,A,bb) for(ch in ccc) cat(ch,:,switch(EXPR = ch, a=1, b=2:3), \n) for(ch in ccc) cat(ch,:,switch(EXPR = ch, a=, A=1, b=2:

文档评论(0)

dmdt5055 + 关注
实名认证
内容提供者

该用户很懒,什么也没介绍

1亿VIP精品文档

相关文档