title: R_2 函数date: 2021-07-11
tags: R语言
categories: 学习
mathjax: true

R语言中的函数

1. 函数的调用

通过“函数名(参数)”的形式可以调用函数。可以将函数的返回值存储在变量中,如果函数返回值需要立即使用也可以不存储在变量中,这叫做“匿名变量”。

2. 基础函数

R内置了一些函数,如表2.1.

表2.1 一些内置函数

函数名 功能
print() 打印
min() 求最小值
sqrt() 开方
sum() 求和
round() 取整
toupper() 返回大写字母
paste() 字符连接
nchar() 统计字符数
c() 连接成向量
seq() 返回序列

3. 必需参数和可选参数

必需参数必须提供参数值,而可选参数可以不提供。可选参数常用命名参数指定。命名参数具有默认值且没有固定顺序,使用命名参数可不考虑参数的顺序。

4. 加载函数

通过install.packages()可以加载库函数。

  1. #install.packages("stringr")#注意双引号,install是下载
  2. install.packages("stringr",repos = "http://cran.us.r-project.org")#使用knitr时必须指定CRAN
  3. library("stringr")#总是要用library,将库加载到当前会话中
  4. str_count("Mississippi","i")#对字符串的i计数,注意字符和字符串都可以用双引号,也可以用单引号

5. 编写函数

以下为编写函数的示例。

  1. #本函数名为make_full_name,接受两个参数:名;姓,返回全名
  2. make_full_name<-function(first_name, last_name)
  3. {
  4. full_name<-paste(first_name, last_name)
  5. print(full_name) #定义函数就是会在console出现一系列加号
  6. }
  7. my_name<-make_full_name("Rush", "Hush")

命名方式:蛇形命名法用下划线分隔单词;也可以用点分隔单词。

一个函数包含以下几个部分:

(1)参数是分配给函数的值,注意按顺序传参。命名参数可以不按顺序。

(2)函数体是大括号内的部分。如果函数超过20行,建议拆分为不同的小块。

(3)返回值可以使用return()函数。

6. 调试函数

需要注意在调试函数前先传参,如果逐条运行函数体内的语句将会没有参数。

7.使用条件语句

使用if-else语句进行条件判断,特别注意使用else时,else需要和if的反括号在同一行。

porridge_temp <- 44  #粥的温度是44摄氏度
# if(porridge_temp > 50)
# {
#   print("太热了。")
# }
# else if(porridge_temp < 30)       #错误,else要紧跟上一个大括号
# {
#   print("太冷了。")
# }
temp_judge <- function(temp)
{
  if(porridge_temp > 50)
  {
    print("太热了。")
  }else if(porridge_temp < 30)
  {
    print("太冷了。")
  }else
  {
    print("粥的温度刚好。")
  }
}
temp_judge(porridge_temp)

8. 本章练习

Exercise1

Exercise 1: calling built-in functions

Create a variable my_name that contains your name

my_name <- paste("Hush","Rush")

Create a variable name_length that holds how many letters (including spaces) are in your name (use the nchar() function)

name_length <- nchar(my_name)

Print the number of letters in your name

print(name_length - 1)  #there is a space

Create a variable now_doing that is your name followed by “is programming!” (use the paste() function)

now_doing <- paste(my_name , "is programming!")

Make the now_doing variable upper case

now_doing <- toupper(now_doing)

Bonus

Pick two of your favorite numbers (between 1 and 100) and assign them to variables fav_1 and fav_2

fav_1 <- 2
fav_2 <- 99

Divide each number by the square root of 201 and save the new value in the original variable

fav_1 <- fav_1/sqrt(201)
fav_2 <- fav_1/sqrt(201)

Create a variable raw_sum that is the sum of the two variables. Use the sum() function for practice.

#raw_sum <- fav_1 + fav_2
raw_sum <- sum(fav_1 , fav_2)

Create a variable round_sum that is the raw_sum rounded to 1 decimal place. Use the round() function.

round_sum <- round(raw_sum,1)

Create two new variables round_1 and round_2 that are your fav_1 and fav_2 variables rounded to 1 decimal places

round_1 <- round(fav_1,1)
round_2 <- round(fav_2,1)

Create a variable sum_round that is the sum of the rounded values

sum_round <- sum(round_1,round_2)

Which is bigger, round_sum or sum_round? (You can use the max() function!)

max_round <- max(round_sum,sum_round)

Exercise 2

# Exercise 2: using built-in string functions

# Create a variable `lyric` that contains the text "I like to eat apples and 
# bananas"

lyric <- "I like to eat apples and bananas"

# Use the `substr()` function to extract the 1st through 13th letters from the 
# `lyric`, and store the result in a variable called `intro`
# Use `?substr` to see more about this function

intro <- substr(lyric,1,13)

# Use the `substr()` function to extract the 15th through the last letter of the 
# `lyric`, and store the result in a variable called `fruits`
# Hint: use `nchar()` to determine how many total letters there are!

fruits <- substr(lyric,15,nchar(lyric))

# Use the `gsub()` function to substitute all the "a"s in `fruits` with "ee".
# Store the result in a variable called `fruits_e`
# Hint: see http://www.endmemo.com/program/R/sub.php for a simpmle example (or 
# use `?gsub`)

fruits_e <- gsub("a","ee",fruits)

# Use the `gsub()` function to substitute all the "a"s in `fruits` with "o".
# Store the result in a variable called `fruits_o`

fruits_o <- gsub("a","o",fruits)

# Create a new variable `lyric_e` that is the `intro` combined with the new
# `fruits_e` ending. Print out this variable

lyric_e <- paste(intro,fruits_e)
lyric_e

# Without making a new variable, print out the `intro` combined with the new
# `fruits_o` ending

print(paste(intro,fruits_o))

Exercise 3

# Exercise 3: writing and executing functions

# Define a function `add_three` that takes a single argument and
# returns a value 3 greater than the input

add_three <- function(x)
{
  return(x+3)
}

# Create a variable `ten` that is the result of passing 7 to your `add_three` 
# function

ten <- add_three(7)
print(ten)

# Define a function `imperial_to_metric` that takes in two arguments: a number 
# of feet and a number of inches
# The function should return the equivalent length in meters

imperial_to_metric <- function(feet,inches)
{
  return(feet * 0.3048 + inches * 0.0254)
}

# Create a variable `height_in_meters` by passing your height in imperial to the
# `imperial_to_metric` function
height_in_meters <- imperial_to_metric(4,3)
print(height_in_meters)

Exercise 4

# Exercise 4: functions and conditionals

# Define a function `is_twice_as_long` that takes in two character strings, and 
# returns whether or not (e.g., a boolean) the length of one argument is greater
# than or equal to twice the length of the other.
# Hint: compare the length difference to the length of the smaller string

is_twice_as_long <- function(string1,string2) #This function returns a boolean which is TRUE when lengths equal.
{
  length1 <- nchar(string1)
  length2 <- nchar(string2)
  if(length1 == length2)
  {
    flag <- TRUE
  } else
  {
    flag <- FALSE
  }
  return (flag)
}

# Call your `is_twice_as_long` function by passing it different length strings
# to confirm that it works. Make sure to check when _either_ argument is twice
# as long, as well as when neither are!

test <- is_twice_as_long("abc","bnm")

# Define a function `describe_difference` that takes in two strings. The
# function should return one of the following sentences as appropriate
#   "Your first string is longer by N characters"
#   "Your second string is longer by N characters"
#   "Your strings are the same length!"

describe_difference <- function(first_string,second_string)
{
  len1 <- nchar(first_string)
  len2 <- nchar(second_string)
  dif <- len1 - len2
  if(dif == 0)
  {
    print("Your strings are the same length!")
  } else if(dif > 0)
  {
    print("Your first string is longer by ")
    print(dif)
    print(" characters")
  } else if(dif < 0)
  {
    print("Your second string is longer by ")
    print(abs(dif))
    print(" characters")
  }
}

# Call your `describe_difference` function by passing it different length strings
# to confirm that it works. Make sure to check all 3 conditions1

describe_difference("abcabc","bcdbcd")
describe_difference("abcabc","bcd")
describe_difference("abc","bcdbcd")