R语言各种方法总结及实例

本文介绍了R语言中的条件控制语句,包括if-else和switch,并展示了for、while和repeat等循环语句的用法。同时,通过实例详细讲解了如何创建和调用用户自定义函数。此外,还探讨了R语言的一元和多元函数优化问题,并介绍了数据整合与重塑的方法,如aggregate函数和reshape包的使用。
摘要由CSDN通过智能技术生成

R语言的条件控制语句

条件控制语句--

1if-else语句

2switch语句

 

If-else语句

(1):if(cond) statement_1

(2):if(cond) statement_1

       else statement_2

(3)Ifelse

 

用法实例:

> x<-3

> #运行完之后值存放在y中

> if(x>2) y<-2*x else y<-3*x

> x

[1] 3

> y

[1] 6

> #运行完之后不仅将值存放在y中,还会将值返回

> x<-1> ifelse(x>2,y<-2*x,y<-3*x)

[1] 3

> y

[1] 3

Swith()循环:

实例:

> #第一个参数表示运行后面第几个表达式

> switch (1,2*3,sd(1:5),runif(3))

[1] 6

> switch (2,2*3,sd(1:5),runif(3))

[1] 1.6

> switch (3,2*3,sd(1:5),runif(3))

[1] 0.163 0.095 0.862

> feelings<-c("sad","afraid")

> for (i in feelings) {

+   print(

+     switch (i,happy="I am glad you are happy",

+             afraid="There is nothing to fear",

+             sad="Cheer up",

+             angry="Calm down now"

+     )

+     

+   )

+ }

[1] "Cheer up"

[1] "There is nothing to fear"

> #for不带大括号

> for (i in feelings)

 +   print(

+     switch (i,happy="I am glad you are happy",

+             afraid="There is nothing to fear",

+             sad="Cheer up",

+             angry="Calm down now"

+     )

+     

+   )

[1] "Cheer up"

[1] "There is nothing to fear"

 

 

循环语句

1)for语句

2)while语句

3)repeat语句

 

一、for循环

二、While循环

三、Repeat循环

实例:

> #for

> Fibonacci<-NULL

> mode(Fibonacci)

[1] "NULL"

> Fibonacci[1]<-Fibonacci[2]<-1

> n=16> for (i in 3:n) {

+   Fibonacci[i]<-Fibonacci[i-2]

+Fibonacci[i-1]

+ }

> #while

> i<-3

> while(Fibonacci[i-2]

+Fibonacci[i-1]<1000){

+   Fibonacci[i]<-Fibonacci[i-2]

+Fibonacci[i-1]

+   i<-i+1

+   }

> Fibonacci

  [1]   1   1   2   3   5   8  13  21  34  55  89 144 233 377 610 987

> i<-1

> while(Fibonacci[i]+Fibonacci[i+1]<1000){

+   Fibonacci[i+2]<-Fibonacci[i]+Fibonacci[i+1]

+   i<-i+1

+ }

> Fibonacci

 [1]   1   1   2   3   5   8  13  21  34  55  89 144 233 377 610 987

 > i<-1

> repeat{

+   Fibonacci[i+2]<-Fibonacci[i]+Fibonacci[i+1]

+   i<-i+1

+   if(F
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值