R语言笔记(四):函数

文章目录

  • 一、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.mzph.cn/bicheng/57676.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

从零开始学python必看,最强“Python编程三剑客(pdf)”

目录 三剑客PDF传送门&#xff1a;三剑客 第一本&#xff1a;《Python编程&#xff1a;从入门到实践》 1.1《Python编程&#xff1a;从入门到实践》第一部分&#xff1a;基础知识 1.2《Python编程&#xff1a;从入门到实践》第二部分&#xff1a;项目 第二本&#xff1a;《…

Metasploit渗透测试之模块学习与开发

# 概述 Metasploit 框架采用模块化架构&#xff0c;即所有漏洞利用、有效载荷、编码器等都以模块形式存在。模块化架构使框架功能的扩展更加容易。任何程序员都可以开发自己的模块&#xff0c;并将其轻松移植到框架中。 # 1、使用辅助模块 在之前的"信息收集和扫描 &qu…

【设计模式-原型】

**原型模式&#xff08;Prototype Pattern&#xff09;**是一种创建型设计模式&#xff0c;旨在通过复制现有对象的方式来创建新对象&#xff0c;而不是通过实例化类来创建对象。该模式允许对象通过克隆&#xff08;复制&#xff09;来创建新的实例&#xff0c;因此避免了重新创…

QT-使用QSS美化UI界面

一、QSS简介&#xff1a; Qt Style Sheet&#xff1a;Qt样式表&#xff0c;用来自定义控件外观的一种机制&#xff0c;可以把他类比成CSS&#xff08;CSS主要功能与最终目的都是能使界面的表现与界面的元素分离&#xff09;。QSS机制使应用程序也能像web界面那样随意地改变外观…

构建后端为etcd的CoreDNS的容器集群(二)、下载最新的etcd容器镜像

在尝试获取etcd的容器的最新版本镜像时&#xff0c;使用latest作为tag取到的并非最新版本&#xff0c;本文尝试用实际最新版本的版本号进行pull&#xff0c;从而取到想的最新版etcd容器镜像。 一、用latest作为tag尝试下载最新etcd的镜像 1、下载镜像 [rootlocalhost opt]# …

基于vue框架的的高校消防设施管理系统06y99(程序+源码+数据库+调试部署+开发环境)系统界面在最后面。

系统程序文件列表 项目功能&#xff1a;设备分类,设备信息,维修人员,报修信息,维修进度,院系,消防知识,培训记录,培训信息,备件信息,备件申请,派发信息,采购信息 开题报告内容 基于Vue框架的高校消防设施管理系统开题报告 一、项目背景与意义 随着高校规模的不断扩大和校园建…

OpenCV和HALCON

OpenCV和HALCON是两种广泛用于图像处理和计算机视觉的开发库&#xff0c;它们各有优缺点&#xff0c;适合不同的应用场景。以下是两者的比较&#xff1a; 1. 开发背景与定位 OpenCV (Open Source Computer Vision Library)&#xff1a; 开源库&#xff0c;最初由Intel开发&…

【EmbeddedGUI】PFB设计说明

PFB设计说明 背景介绍 一般来说&#xff0c;要实现屏幕显示&#xff0c;就是向特定像素点写入颜色值&#xff0c;最简单的办法就是直接通过SPI接口&#xff0c;向显示器芯片的特定缓存地址&#xff0c;写入像素点。一般来说&#xff0c;显示器芯片会提供2个基本操作API&#…

qt QNetworkProxy详解

一、概述 QNetworkProxy通过设置代理类型、主机、端口和认证信息&#xff0c;可以使应用程序的所有网络请求通过代理服务器进行。它支持为Qt网络类&#xff08;如QAbstractSocket、QTcpSocket、QUdpSocket、QTcpServer、QNetworkAccessManager等&#xff09;配置网络层代理支持…

数据仓库基础概念

数据仓库 概念 数据仓库&#xff08;Data Warehouse, DW&#xff09;是一个面向主题的、集成的、相对稳定的、反映历史变化的数据集合。它是为满足企业决策分析需求而设计的。 面向主题&#xff1a;数据仓库围绕特定的主题组织数据&#xff0c;例如“销售”或“人力资源”&am…

学成在线实战

#1024程序员节&#xff5c;征文# 一、Bug修改 在实战之前&#xff0c;老师留了一个bug&#xff0c;这个bug出现的原因是因为在查询课程计划时&#xff0c;使用的是Inner join查询&#xff0c;所以当章节下面没有小节的时候&#xff0c;是查不出来数据的&#xff0c;只需要将其…

PHP企业门店订货通进销存系统小程序源码

订货通进销存系统&#xff0c;企业运营好帮手&#xff01; &#x1f4e6; 开篇&#xff1a;告别繁琐&#xff0c;企业运营新选择 嘿&#xff0c;各位企业主和创业者们&#xff01;今天我要给大家介绍一款超实用的企业运营神器——“订货通进销存系统”。在这个数字化时代&…

YOLOv5_DeepSORT实现电动自行车头盔佩戴检测系统

获取更多完整项目代码数据集&#xff0c;点此加入免费社区群 &#xff1a; 首页-置顶必看 文档说明 本文档是毕业设计——基于深度学习的电动自行车头盔佩戴检测系统的开发环境配置说明文档&#xff0c;该文档包括运行环境说明以及基本环境配置两大部分。在程序运行前请认真查…

零售行业的数字化营销转型之路

一方面&#xff0c;市场竞争激烈&#xff0c;电商平台、新兴品牌和跨界对手带来巨大压力。另一方面&#xff0c;消费者需求变化迅速&#xff0c;更加追求个性化、多元化和便捷化的购物体验&#xff0c;同时传统零售企业还面临着高成本压力&#xff0c;如租金、人力和库存等。 然…

Rsync数据复制/备份服务应用

文章目录 1. rsync概述1.1 什么是Rsync1.2 rsync的功能1.3 rsync 的功能特性1.4 Rsync 增量复制原理1.5 生产场景架构集群备份方案 2. Rsync工作方式介绍与实践2.1 本地数据传输模式2.1.1 本地数据传输模式语法2.1.2 本地数据传输模式实践 2.2 远程Shell 数据传输模式2.2.1 远程…

数据结构练习题5(链表和栈)

1环形链表 II 给定一个链表的头节点 head &#xff0c;返回链表开始入环的第一个节点。 如果链表无环&#xff0c;则返回 null。 如果链表中有某个节点&#xff0c;可以通过连续跟踪 next 指针再次到达&#xff0c;则链表中存在环。 为了表示给定链表中的环&#xff0c;评测…

全面指南:中国人工智能大模型技术创新与应用

近期&#xff0c;中国人工智能协会发布了《中国人工智能大模型技术白皮书》&#xff0c;涵盖了大模型发展历程、关键技术、困难及挑战以及未来发展的展望。 在此本文总结了下白皮书的主要内容&#xff0c;并附上白皮书~ 目录第 1 章 大模型技术概述 ........................…

基础数据结构——队列(双端队列,优先级队列,阻塞队列)

双端队列、队列、栈对比 定义特点队列一端删除&#xff08;头&#xff09;另一端添加&#xff08;尾&#xff09;First In First Out栈一端删除和添加&#xff08;顶&#xff09;Last In First Out双端队列两端都可以删除、添加优先级队列优先级高者先出队延时队列根据延时时间…

微信小程序地图功能开发:绘制多边形和标记点

在微信小程序中&#xff0c;地图功能是一个常见的需求&#xff0c;尤其是在需要展示地理位置、导航指引或区域覆盖的应用中。本文将通过一个实际的微信小程序地图组件示例&#xff0c;介绍如何在地图上绘制多边形区域和标记点&#xff0c;以及如何响应用户的点击事件。 项目背景…

V2X介绍

文章目录 什么是V2XV2X的发展史早期的DSRC后起之秀C-V2XC-V2X 和DSRC 两者的对比 什么是V2X 所谓V2X&#xff0c;与流行的B2B、B2C如出一辙&#xff0c;意为vehicle to everything&#xff0c;即车对外界的信息交换。车联网通过整合全球定位系统&#xff08;GPS&#xff09;导…