R语言笔记(四):函数

news/2024/10/28 23:22:43/

文章目录

  • 一、Function basics
    • 1、Creating your own function
    • 2、Function structure
    • 3、Using your created function
    • 4、Multiple inputs
    • 5、Default inputs
  • 二、Return values and side effects
    • 1、Returning more than one thing
    • 2、Side effects
      • Example of side effect: plot
  • 三、Environments and design
    • 1、Environment: what the function can see and do
    • 2、Environment examples


一、Function basics

1、Creating your own function

Call function() to create your own function. Document your function with comments

# get.wordtab.king: get a word table from King's "I Have A Dream" speech
# Input: none
# Output: word table, i.e., vector with counts as entries and associated
#         words as namesget.wordtab.king = function() {lines = readLines("https://raw.githubusercontent.com/king.txt")text = paste(lines, collapse=" ")words = strsplit(text, split="[[:space:]]|[[:punct:]]")[[1]]words = words[words != ""]wordtab = table(words)return(wordtab)
}
  • Input: none
  • Output: word table, i.e., vector with counts as entries and associated words as names

Much better: create a word table function that takes a URL of web

# get.wordtab.from.url: get a word table from text on the web
# Input:
# - str.url: string, specifying URL of a web page 
# Output: word table, i.e., vector with counts as entries and associated
#   words as namesget.wordtab.from.url = function(str.url) {lines = readLines(str.url)text = paste(lines, collapse=" ")words = strsplit(text, split="[[:space:]]|[[:punct:]]")[[1]]words = words[words != ""]wordtab = table(words)return(wordtab)
}
  • Input:

    • str.url: string, specifying URL of a web page
  • Output: word table, i.e., vector with counts as entries and associated words as names

2、Function structure

The structure of a function has three basic parts:

  • Inputs (or arguments): within the parentheses of function()
  • Body (code that is executed): within the braces {}
  • Output (or return value): obtained with function return()
  • (optional) Comments: description of functions by comments
# get.wordtab.from.url: get a word table from text on the web
# Input:
# - str.url: string, specifying URL of a web page 
# Output: word table, i.e., vector with counts as entries and associated
#   words as namesget.wordtab.from.url = function(str.url) {lines = readLines(str.url)text = paste(lines, collapse=" ")words = strsplit(text, split="[[:space:]]|[[:punct:]]")[[1]]words = words[words != ""]wordtab = table(words)return(wordtab)
}

3、Using your created function

Our created functions can be used just like the built-in ones

# Using our function
king.wordtab.new = get.wordtab.from.url("https://raw.githubusercontent.com/mxcai/BIOS5801/main/data/king.txt")
all(king.wordtab.new == king.wordtab)
## [1] TRUE# Revealing our function's definition
get.wordtab.from.url
## function(str.url) {
## lines = readLines(str.url)
## text = paste(lines, collapse=" ")
## words = strsplit(text, split="[[:space:]]|[[:punct:]]")[[1]]
## words = words[words != ""]
## wordtab = table(words)
## return(wordtab)
## }

4、Multiple inputs

Our function can take more than one input

# get.wordtab.from.url: get a word table from text on the web
# Inputs:
# - str.url: string, specifying URL of a web page 
# - split: string, specifying what to split on
# Output: word table, i.e., vector with counts as entries and associated
#   words as namesget.wordtab.from.url = function(str.url, split) {lines = readLines(str.url)text = paste(lines, collapse=" ")words = strsplit(text, split=split)[[1]]words = words[words != ""]table(words)
}
  • Inputs:
  • str.url: string, specifying URL of a web page
  • split: string, specifying what to split on
  • Output: word table, i.e., vector with counts as entries and associated words as names

5、Default inputs

Our function can also specify default values for the inputs (if the user doesn’t specify an input in the function call, then the default value is used)

# get.wordtab.from.url: get a word table from text on the web
# Inputs:
# - str.url: string, specifying URL of a web page 
# - split: string, specifying what to split on. Default is the regex pattern
#   "[[:space:]]|[[:punct:]]"
# - convert2lower: Boolean, TRUE if words should be converted to lower case before
#   the word table is computed. Default is TRUE
# Output: word table, i.e., vector with counts as entries and associated
#   words as namesget.wordtab.from.url = function(str.url, split="[[:space:]]|[[:punct:]]", convert2lower=TRUE) {lines = readLines(str.url)text = paste(lines, collapse=" ")words = strsplit(text, split=split)[[1]]words = words[words != ""]# Convert to lower case, if we're asked toif (convert2lower) words = tolower(words)table(words)
}

二、Return values and side effects

1、Returning more than one thing

R doesn’t let your function have multiple outputs, but you can return a list

When creating a function in R, though you cannot return more than one output, you can return a list. This (by definition) can contain an arbitrary number of arbitrary objects

  • Inputs:
    • str.url: string, specifying URL of a web page
    • split: string, specifying what to split on. Default is the regex pattern “[[:space:]]|[[:punct:]]”
    • convert2lower: Boolean, TRUE if words should be converted to lower case before the word table is computed. Default is TRUE
    • keep.nums: Boolean, TRUE if words containing numbers should be kept in the word table. Default is FALSE
  • Output: list, containing word table, and then some basic numeric summaries
get.wordtab.from.url = function(str.url, split="[[:space:]]|[[:punct:]]",convert2lower=TRUE, keep.nums=FALSE) {lines = readLines(str.url)text = paste(lines, collapse=" ")words = strsplit(text, split=split)[[1]]words = words[words != ""]# Convert to lower case, if we're asked toif (convert2lower) {words = tolower(words)}# Get rid of words with numbers, if we're asked toif (!keep.nums) {words = grep("[0-9]", words, invert=TRUE, value=TRUE)}# Compute the word tablewordtab = table(words)return(list(wordtab=wordtab,number.unique.words=length(wordtab),number.total.words=sum(wordtab),longest.word=words[which.max(nchar(words))]))
}
# King's "I Have A Dream" speech 
king.wordtab = get.wordtab.from.url("https://raw.githubusercontent.com/king.txt")
lapply(king.wordtab, head)## $wordtab
## words
## a able again ago ahead alabama
## 37 8 2 1 1 3
##
## $number.unique.words
## [1] 528
##
## $number.total.words
## [1] 1631
##
## $longest.word
## [1] "discrimination"

2、Side effects

A side effect of a function is something that happens as a result of the function’s body, but is not returned. Examples:

  • Printing something out to the console
  • Plotting something on the display
  • Saving an R data file, or a PDF, etc.

Example of side effect: plot

  • get.wordtab.from.url: get a word table from text on the web
  • Inputs:
    • str.url: string, specifying URL of a web page
    • split: string, specifying what to split on. Default is the regex pattern “[[:space:]]|[[:punct:]]”
    • convert2lower: Boolean, TRUE if words should be converted to lower case before the word table is computed. Default is TRUE
    • keep.nums: Boolean, TRUE if words containing numbers should be kept in the word table. Default is FALSE
    • plot.hist: Boolean, TRUE if a histogram of word lengths should be plotted as a side effect. Default is FALSE
  • Output: list, containing word table, and then some basic numeric summaries
get.wordtab.from.url = function(str.url, split="[[:space:]]|[[:punct:]]",convert2lower=TRUE, keep.nums=FALSE, plot.hist=FALSE) {lines = readLines(str.url)text = paste(lines, collapse=" ")words = strsplit(text, split=split)[[1]]words = words[words != ""]# Convert to lower case, if we're asked toif (convert2lower) words = tolower(words)# Get rid of words with numbers, if we're asked toif (!keep.nums) words = grep("[0-9]", words, invert=TRUE, value=TRUE)# Plot the histogram of the word lengths, if we're asked toif (plot.hist) hist(nchar(words), col="lightblue", breaks=0:max(nchar(words)),xlab="Word length")# Compute the word tablewordtab = table(words)return(list(wordtab=wordtab,number.unique.words=length(wordtab),number.total.words=sum(wordtab),longest.word=words[which.max(nchar(words))]))
}
# King's speech
king.wordtab = get.wordtab.from.url(str.url="https://raw.githubusercontent.com/mxcai/BIOS5801/main/data/king.txt",plot.hist=TRUE)

在这里插入图片描述


三、Environments and design

1、Environment: what the function can see and do

  • Each function generates its own environment
  • Variable names in function environment override names in the global environment
  • Internal environment starts with the named arguments
  • Assignments inside the function only change the internal environment
  • Variable names undefined in the function are looked for in the global environment

2、Environment examples

  • Variable names here override names in the global environment

    • y is 2 in the global environment
    • y is 10 in the function environment, and only exists when the function is under execution
  • Variable assignments inside the function environment would (generally) not change the variable in the global environment

    • x remains to be 1 in the global environment
x <- 1
y <- 2
addone = function(y) { x = 1+yx 
}
addone(10)
## [1] 11y
## [1] 2x
## [1] 1
  • Variable names undefined in the function are looked for in the global environment
circle.area = function(r) { pi*r^2 }
circle.area(1:3)
## [1] 3.141593 12.566371 28.274334true.pi = pi # to back up the sanity
pi = 3 
circle.area(1:3)
## [1] 3 12 27pi = true.pi # Restore sanity
circle.area(1:3)
## [1] 3.141593 12.566371 28.274334

http://www.ppmy.cn/news/1542710.html

相关文章

Xcode真机运行正常,打包报错

1.问题&#xff1a; 老项目Xcode真机运行没问题&#xff0c;但但打包的时候却报了以下错误&#xff1a; some files could not be transferred (code 23) at /AppleInternal/Library/BuildRoots/4ff29661-3588-11ef-9513-e2437461156c/Library/Caches/com.apple.xbs/Sources/r…

FreeSWITCH JSON API

仅举几例&#xff1a; fs_cli -x json {"command" : "status", "data" : ""} fs_cli -x json {"command" : "sofia.status", "data" : ""} fs_cli -x json {"command" : "…

从零开始学PHP之函数

函数 概念 函数是通过调用函数来执行的。emmm这个是官方解释&#xff0c;函数就是封装一段用于完成特定功能的代码。 通俗理解函数&#xff1a;可以完成某个工作的代码块&#xff0c;就像小朋友搭房子用的积木一样&#xff0c;可以反复使用&#xff0c;在使用的时候&#xff…

【若依笔记】-- 精简若依项目只保留系统管理

环境&#xff1a;最近项目需要计划使用若依来开发软件&#xff0c;使用若依有一个问题&#xff0c;若依代码框架还是比较冗余&#xff0c;不够精简&#xff0c;还有一点是若依Security权限校验&#xff0c;对于实现一对多的前台&#xff0c;比较麻烦&#xff0c;我这边的业务是…

Spring Boot 实现文件分片上传和下载

文章目录 一、原理分析1.1 文件分片1.2 断点续传和断点下载1.2 文件分片下载的 HTTP 参数 二、文件上传功能实现2.1 客户端(前端)2.2 服务端 三、文件下载功能实现3.1 客户端(前端)3.2 服务端 四、功能测试4.1 文件上传功能测试4.2 文件下载功能实现 参考资料 完整案例代码&…

sqlyog连接MySQL8.4报1251错误

查看插件状态 1 show plugins; 看看mysql_native_password插件的状态是不是ACTIVE,如果状态值为DISABLED则说明插件没有激活 3) 修改my.cnf或my.ini配置文件&#xff0c;添加mysql_native_passwordON 1 2 [mysqld] mysql_native_passwordON 4) 重启mysql服务 5) mysq…

预测房价学习

1. 实现函数来方便下载数据 import hashlib import os import tarfile import zipfile import requestsDATA_HUB dict() DATA_URL http://d2l-data.s3-accelerate.amazonaws.com/def download(name, cache_diros.path.join(.., data)):"""下载一个DATA_HUB中…

医疗保健知识中台:引领医疗行业智能化转型的新篇章

前言 随着科技的迅猛进步&#xff0c;医疗保健领域正迎来一场深刻的智能化变革。在这场变革中&#xff0c;知识中台作为医疗行业智能化升级的重要基石&#xff0c;正逐步成为提升医疗服务质量和效率的关键驱动力。本文将深入剖析医疗保健知识中台的内容构成、应用场景以及更新…