R语言小白学习笔记5—编写R语言函数和简单的控制循环语句

笔记链接

学习笔记1—R语言基础.
学习笔记2—高级数据结构.
学习笔记3—R语言读取数据.
学习笔记4—统计图.

学习笔记5—编写R语言函数和简单的控制循环语句

因为控制语句和循环语句的语法都比较简单,所以我直接把这三章的内容总结到一起了,主要以例子为主,加深理解。

5.1 编写R语言函数

如果有不断重复的相同代码,那么可能需要编写函数

5.1.1 Hello, World

例:

> say.hello <- function()
+ {
+     print("Hello, World!")
+ }

这里的换行shift+enter

在R语句中,"."只是一个简单的字符,并没有特殊含义(这里有一些例外,但不影响我们的使用)

打印:

> say.hello()
[1] "Hello, World!"

5.1.2 函数参数

先了解sprintf函数

该函数的第一个参数是带有特殊输入字符的字符串,第二个参数会代替前面的特殊输入字符。

> sprintf("Hello %s", "Jared")
[1] "Hello Jared"
> sprintf("Hello %s, today is %s", "Jared", "Sunday")
[1] "Hello Jared, today is Sunday"

为函数增加参数:

> hello.person <- function(first,last)
+ {
+     print(sprintf("Hello %s %s", first, last))
+ }
> hello.person("Bob", "Lander")
[1] "Hello Bob Lander"

默认参数:

默认last参数值为"Doe":

> hello.person <- function(first,last="Doe")
+ {
+     print(sprintf("Hello %s %s", first, last))
+ }
> hello.person("Bob")
[1] "Hello Bob Doe"
> hello.person("Bob", "Lander")
[1] "Hello Bob Lander"

默认参数可以改变

额外参数

操作符""允许函数具有任意数量的操作符,但要小心使用:

加入额外参数前:

> hello.person("Bob", extra = "Lander")
Error in hello.person("Bob", extra = "Lander") : 
  参数没有用(extra = "Lander")
> hello.person("Bob", "Lander", "Goodbye")
Error in hello.person("Bob", "Lander", "Goodbye") : 参数没有用("Goodbye")

加入额外参数后:

> hello.person <- function(first,last="Doe", ...)
+ {
+     print(sprintf("Hello %s %s", first, last))
+ }
> hello.person("Bob", extra = "Lander")
[1] "Hello Bob Doe"
> hello.person("Bob", "Lander", "Goodbye")
[1] "Hello Bob Lander"

5.1.3 返回值

两种方式:

函数最后一行代码自动返回函数值(不推荐)

使用return命令返回,同时函数退出

例:

> double.num <- function(x)
+ {
+     return(x*2)
+ }
> double.num(5)
[1] 10

5.1.1 do.call函数

do.call函数允许指定一个函数的名称(字符型或者对象),并提供相应的参数(列表):

> do.call("hello.person", args = list(first="Jared", last="Lander"))
[1] "Hello Jared Lander"
> do.call(hello.person, args = list(first="Jared", last="Lander"))
[1] "Hello Jared Lander"

这在创建用户指定行为的函数时特别有用

例,用户提供一个向量和函数:

> run.this <- function(x, func=mean)
+ {
+     do.call(func, args=list(x))
+ }
> run.this(1:10)
[1] 5.5
> run.this(1:10, mean)
[1] 5.5
> run.this(1:10, sum)
[1] 55
> run.this(1:10, sd)
[1] 3.02765

5.2 控制语句

控制语句在其他编程软件里边很常见了,所以我就简单举几个例子。

5.2.1 if和else语句

> check.bool <- function(x)
+ {
+     if(x == 1)
+     {
+         print("hello")
+     }else
+     {
+         print("goodbye")
+     }
+ }
> check.bool(1)
[1] "hello"
> check.bool("k")
[1] "goodbye"
> check.bool(TRUE)
[1] "hello"

注意,else语句跟前边的右大括号(})同行,否则会报错。

TRUE在数值上与1相同,所以输入TRUE会打印hello

5.2.2 switch语句

同样,举个简单的例子:

> use.switch <- function(x)
+ {
+     switch(x,
+            "a"="first",
+            "b"="second",
+            "z"="last",
+            "c"="third",
+            "other")
+ }
> use.switch("a")
[1] "first"
> use.switch(1)
[1] "first"
> use.switch("d")
[1] "other"
> use.switch(5)
[1] "other"
> use.switch(6)
> is.null(use.switch(6))
[1] TRUE

如果参数是数字,函数会按照位置进行匹配,如果数字参数大于后续的参数量,则返回NULL

5.2.3 ifelse函数

ifelse函数的第个参数为被检查的条件,第个参数为条件检查时TRUE的返回值,第个参数为条件检查时FALSE的返回值

> toTest <- c(1, 1, 0, 1, 0)
> ifelse(toTest == 1, "Yes", "No")
[1] "Yes" "Yes" "No"  "Yes" "No" 
> ifelse(toTest == 1, toTest*3, "Zero")
[1] "3"    "3"    "Zero" "3"    "Zero"

5.2.4 复合检查

例:

> a <- c(1, 1, 0, 1)
> b <- c(2, 1, 0, 1)
> ifelse(a == 1 & b == 1, "Yes", "No")
[1] "No"  "Yes" "No"  "Yes"
> ifelse(a == 1 && b == 1, "Yes", "No")
[1] "No"

双符号形式(&&或者||)用于if条件检查,单符号形式(&或者|)用于ifelse检查。

双符号仅比较两边的一个元素单符号比较两边的每个元素

单符号和双符号的处理过程也不同。当使用单符号时,运算符两边都要检查,使用双符号时,有时只有左边需要检查。

如&&,当左边检查FALSE时就没有理由检查右边了。

5.3 R语言的循环迭代

5.3.1 for循环

for声明循环传入含有三部分的一个参数,第部分为任意类型的向量,第个部分是迭代的变量,它从第三部分的向量取值,中间部分是简单的单词"in"

for循环中的向量不一定是连续的,它可以是任意向量

> friut <- c("apple", "banana", "pomegranate")
> fruit <- c("apple", "banana", "pomegranate")
> fruitLength <- rep(NA, length(fruit))
> fruitLength
[1] NA NA NA
> names(fruitLength) <- fruit
> fruitLength
      apple      banana pomegranate 
         NA          NA          NA 
> for(a in fruit)
+ {
+     fruitLength[a] <- nchar(a)
+ }
> fruitLength
      apple      banana pomegranate 
          5           6          11 

5.3.2 while循环

例:

> x <- 1
> while(x <= 5)
+ {
+     print(x)
+     x <- x + 1
+ }
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5

5.3.3 控制循环

有时必须跳出下一个迭代或者完全终止迭代,由next函数和break函数实现

例:

> for(i in 1:10)
+ {
+     if(i == 3)
+     {
+         next
+     }
+     print(i)
+ }
[1] 1
[1] 2
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10
> for(i in 1:10)
+ {
+     if(i == 4)
+     {
+         break
+     }
+     print(i)
+ }
[1] 1
[1] 2
[1] 3
  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值