R语言笔记(五):Apply函数

news2024/10/28 13:23:21

文章目录

  • 一、Apply Family
  • 二、`apply()`: rows or columns of a matrix or data frame
  • 三、Applying a custom function
  • 四、Applying a custom function "on-the-fly"
  • 五、Applying a function that takes extra arguments
  • 六、What's the return argument?
  • 七、Optimized functions for special tasks
  • 八、`lapply`: elements of a list or vector
  • 九、`sapply()`: elements of a list or vector
  • 十、`tapply()`: levels of a factor vector
  • 十一、`split()`: split by levels of a factor


一、Apply Family

R offers a family of apply functions, which allow you to apply a function across different chunks of data. Offers an alternative to explicit iteration using for() loop; can be simpler and faster, though not always. Summary of functions:

  • apply(): apply a function to rows or columns of a matrix or data frame
  • lapply(): apply a function to elements of a list or vector
  • sapply(): same as the above, but simplify the output (if possible)
  • tapply(): apply a function to levels of a factor vector

二、apply(): rows or columns of a matrix or data frame

The apply() function takes inputs of the following form:

  • apply(x, MARGIN=1, FUN=my.fun), to apply my.fun() across rows of a matrix or data frame x
  • apply(x, MARGIN=2, FUN=my.fun), to apply my.fun() across columns of a matrix or data frame x
apply(state.x77, MARGIN=2, FUN=sum) # Minimum entry in each column
## Population Income Illiteracy Life Exp Murder HS Grad
## 212321.00 221790.00 58.50 3543.93 368.90 2655.40
## Frost Area
## 5223.00 3536794.00

colSums(state.x77)
## Population Income Illiteracy Life Exp Murder HS Grad
## 212321.00 221790.00 58.50 3543.93 368.90 2655.40
## Frost Area
## 5223.00 3536794.00
  • When output of the function passed to FUN is a single value, apply() output a vector across the columns/rows
apply(state.x77, MARGIN=2, FUN=which.max) # Index of the max in each column
## Population Income Illiteracy Life Exp Murder HS Grad
## 5 2 18 11 1 44
## Frost Area
## 28 2
  • When output of the function passed to FUN is a vector, apply() output a matrix across the columns/rows
apply(state.x77, MARGIN=2, FUN=summary) 

在这里插入图片描述


三、Applying a custom function

For a custom function, we can just define it before hand, and the use apply() as usual

# Our custom function: second largest value
second.max = function(v) {  
  sorted.v = sort(v,decreasing = T)
  return(sorted.v[2])
}

apply(state.x77, MARGIN=2, FUN=second.max) 
## Population Income Illiteracy Life Exp Murder HS Grad
## 18076.00 5348.00 2.40 72.96 13.90 66.70
## Frost Area
## 186.00 262134.00

apply(state.x77, MARGIN=2, FUN=max) 
## Population Income Illiteracy Life Exp Murder HS Grad
## 21198.0 6315.0 2.8 73.6 15.1 67.3
## Frost Area
## 188.0 566432.0

四、Applying a custom function “on-the-fly”

Instead of defining a custom function before hand, we can define it “on-the-fly”.

# Compute trimmed means, defining this on-the-fly
apply(state.x77, MARGIN=2, FUN=function(v) {  
  sorted.v = sort(v,decreasing = T)
  return(sorted.v[2])
})

## Population Income Illiteracy Life Exp Murder HS Grad
## 18076.00 5348.00 2.40 72.96 13.90 66.70
## Frost Area
## 186.00 262134.00
  • When the custom function is simple, this can be more convenient
# Compute trimmed means, defining this on-the-fly
apply(state.x77, MARGIN=2, FUN=function(v) {sort(v,decreasing = T)[2]})

## Population Income Illiteracy Life Exp Murder HS Grad
## 18076.00 5348.00 2.40 72.96 13.90 66.70
## Frost Area
## 186.00 262134.00

五、Applying a function that takes extra arguments

Can tell apply() to pass extra arguments to the function in question. E.g., can use: apply(x, MARGIN=1, FUN=my.fun, extra.arg.1, extra.arg.2), for two extra arguments extra.arg.1, extra.arg.2 to be passed to my.fun()

# Our custom function: trimmed mean, with user-specified percentiles
kth.max = function(v,k) {  
  sorted.v = sort(v,decreasing = T)
  return(sorted.v[k])
}

apply(state.x77, MARGIN=2, FUN=kth.max, k=10)
## Population Income Illiteracy Life Exp Murder HS Grad
## 5814.00 4903.00 1.80 72.13 11.10 59.90
## Frost Area
## 155.00 96184.00

六、What’s the return argument?

What kind of data type will apply() give us? Depends on what function we pass. Summary, say, with FUN=my.fun():

  • If my.fun() returns a single value, then apply() will return a vector
  • If my.fun() returns k values, then apply() will return a matrix with k rows (note: this is true regardless of whether MARGIN=1 or MARGIN=2)
  • If my.fun() returns different length outputs for different inputs, then apply() will return a list
  • If my.fun() returns a list, then apply() will return a list

七、Optimized functions for special tasks

Don’t overuse the apply paradigm! There’s lots of special functions that optimized are will be both simpler and faster than using apply(). E.g.,

  • rowSums(), colSums(): for computing row, column sums of a matrix
  • rowMeans(), colMeans(): for computing row, column means of a matrix
  • max.col(): for finding the maximum position in each row of a matrix

Combining these functions with logical indexing and vectorized operations will enable you to do quite a lot. E.g., how to count the number of positives in each row of a matrix?

x = matrix(rnorm(9), 3, 3)
# Don't do this (much slower for big matrices)
apply(x, MARGIN=1, function(v) { return(sum(v > 0)) })
## [1] 2 2 1

# Do this insted (much faster, simpler)
rowSums(x > 0)
## [1] 2 2 1

八、lapply: elements of a list or vector

The lapply() function takes inputs as in: lapply(x, FUN=my.fun), to apply my.fun() across elements of a list or vector x. The output is always a list

my.list

## $nums
## [1] 0.1 0.2 0.3 0.4 0.5 0.6
##
## $chars
## [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l"
##
## $bools
## [1] TRUE FALSE FALSE TRUE FALSE TRUE
lapply(my.list, FUN=mean) # Get a warning: mean() can't be applied to chars
## Warning in mean.default(X[[i]], ...): argument is not numeric or
## logical: returning NA
## $nums
## [1] 0.35
##
## $chars
## [1] NA
##
## $bools
## [1] 0.5

lapply(my.list, FUN=summary)
## $nums
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 0.100 0.225 0.350 0.350 0.475 0.600
##
## $chars
## Length Class Mode
## 12 character character
##
## $bools
## Mode FALSE TRUE
## logical 3 3

九、sapply(): elements of a list or vector

The sapply() function works just like lapply(), but tries to simplify the return value whenever possible. E.g., most common is the conversion from a list to a vector

sapply(my.list, FUN=mean) # Simplifies the result, now a vector
## Warning in mean.default(X[[i]], ...): argument is not numeric or
## logical: returning NA
## nums chars bools
## 0.35 NA 0.50
sapply(my.list, FUN=summary) # Can't simplify, so still a list
## $nums
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 0.100 0.225 0.350 0.350 0.475 0.600
##
## $chars
## Length Class Mode
## 12 character character
##
## $bools
## Mode FALSE TRUE
## logical 3 3

十、tapply(): levels of a factor vector

The function tapply() takes inputs as in: tapply(x, INDEX=my.index, FUN=my.fun), to apply my.fun() to subsets of entries in x that share a common level in my.index

# Compute the mean and sd of the Frost variable, within each region
tapply(state.x77[,"Frost"], INDEX=state.region, FUN=mean)
## Northeast South North Central West
## 132.7778 64.6250 138.8333 102.1538

tapply(state.x77[,"Frost"], INDEX=state.region, FUN=sd)
## Northeast South North Central West
## 30.89408 31.30682 23.89307 68.87652

十一、split(): split by levels of a factor

The function split() split up the rows of a data frame by levels of a factor, as in: split(x, f=my.index) to split a data frame x according to levels of my.index

# Split up the state.x77 matrix according to region
state.by.reg = split(data.frame(state.x77), f=state.region)

class(state.by.reg) # The result is a list
## [1] "list"

names(state.by.reg) # This has 4 elements for the 4 regions
## [1] "Northeast" "South" "North Central" "West"

class(state.by.reg[[1]]) # Each element is a data frame
## [1] "data.frame"

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2225452.html

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

相关文章

基于贝叶斯优化的K折交叉验证BP回归模型(可预测未来数据)

基于贝叶斯优化的K折交叉验证BP回归模型(可预测未来数据) 目录 基于贝叶斯优化的K折交叉验证BP回归模型(可预测未来数据)效果一览基本介绍程序设计参考资料 效果一览 基本介绍 基于贝叶斯优化的K折交叉验证BP回归模型的多输入单一输出回归模型 Matlab版本:2020a及以…

深度学习_循环神经网络_预测平安中国股价(文末附带数据集下载链接, 长期有效, 如果有大佬愿意帮忙, 我先在这磕一个,感谢)

简介: 使用循环神经网络RNN对股价进行预测, 也就是搭建循环神经网络对中国平安的收盘股价进行预测 深度学习训练流程 1.数据集导入 2.数据预处理 3.模型训练 模型结构要求: 单层简单R…

U盘恢复数据,这四款软件你必须知道!

不管是哪个行业哪个职位,数据安全都是很重要的。比如说我认识的财务姐姐,每天处理的财务报表、客户信息、合同文件等,都必须确保万无一失,尤其是各种U盘数据。为了防止数据丢失后找不到数据的情况,今天来和大家分享四款…

智能管线巡检系统:强化巡检质量,确保安全高效运维

线路巡检质量的监控是确保线路安全、稳定运行的重要环节。为了有效监控巡检质量,采用管线巡检系统是一种高效、科学的手段。以下是对如何通过管线巡检系统实现线路巡检质量监控的详细分析: 一、巡检速度监控 管线巡检系统能够实时监控巡检人员的巡检速度…

算力引领 智慧安防| Gooxi助力安防行业智慧化转型

安防行业作为AI最为合适生长的天然场域,早在国内AI市场爆发之前就提前进行了“预演”,诞生了AI四小龙。当AIGC赋能安防技术革新,安防再次与AI浪潮撞了个满怀。在这一次大模型的浪潮中,安防场上的老玩家纷纷抢滩大模型。而今&#…

Word中Normal.dotm样式模板文件

Normal.dotm文档 首先将自己电脑中C:\Users\自己电脑用户名\AppData\Roaming\Microsoft\Templates路径下的Normal.dotm文件做备份,在下载本文中的Normal.dotm文件,进行替换,重新打开word即可使用。 字体样式如下(可自行修改&#…

Redis 发布订阅 总结

前言 相关系列 《Redis & 目录》(持续更新)《Redis & 发布订阅 & 源码》(学习过程/多有漏误/仅作参考/不再更新)《Redis & 发布订阅 & 总结》(学习总结/最新最准/持续更新)《Redis &a…

git的学习之远程进行操作

1.代码托管GitHub:充当中央服务器仓库的角色 2.git远程进行操作 3.配置本地服务器的公钥 4.推送 5.git远程操作 pull .gitignore 6.给命令配置别名 git config --global alias.st status 7.标签管理 git tag -a [name] -m "XXX" [commit_id] 操作标签…

ICMP Redirect Attack Lab

本实验的网络拓扑图如下所示: Task 1: Launching ICMP Redirect Attack 在Victim主机上查看路由表,结果如下: 2.在Victim上Ping 192.168.60.60.5,结果如下: 3.在Attkaker主机上创建redirect_attack.py文件, 内容如下: 4.接下来查看tracerou…

纯GO语言开发RTSP流媒体服务器-RTSP推流直播、本地保存录像、录像回放、http-flv及hls协议分发

温馨提示:我们分享的文章是给需要的人,不需要的人请绕过,文明浏览,误恶语伤人! 前言 在软件开发中遇到使用流媒体音视频的行业比较多,如安防监控系统、无人机巡逻视频上云处理、直播平台、教育与企业培训…

C++红黑树插入操作的模拟实现

1.红黑树概念 1.1什么是红黑树 红黑树,是一种二叉搜索树,但在每个结点上增加一个存储位表示结点的颜色,可以是Red或 Black。 通过对任何一条从根到叶子的路径上各个结点着色方式的限制,红黑树确保没有一条路径会比其他路径长出俩…

Linux 重启命令全解析:深入理解与应用指南

Linux 重启命令全解析:深入理解与应用指南 在 Linux 系统中,掌握正确的重启命令是确保系统稳定运行和进行必要维护的关键技能。本文将深入解析 Linux 中常见的重启命令,包括功能、用法、适用场景及注意事项。 一、reboot 命令 功能简介 re…

Flutter图片控件(七)

1、加载图片 import package:flutter/material.dart;void main() {runApp(const MaterialApp(home: MyHomePage(),)); }class MyHomePage extends StatelessWidget {const MyHomePage({super.key});overrideWidget build(BuildContext context) {return Scaffold(appBar: AppB…

Python:背景知识及环境安装

一、计算机的基础概念 1.1 什么是计算机? 最早我们有计算器,但是他只能完成算数运算的功能 而计算机能完成的工作有: (1)算术运算 (2)逻辑判断 (3)数据存储 &#xff08…

k8s 二进制部署安装(一)

目录 环境准备 初始化操作系统 部署docker 引擎 部署 etcd 集群 准备签发证书环境 部署 Master01 服务器相关组件 apiserver scheduler controller-manager.sh admin etcd 存储了 Kubernetes 集群的所有配置数据和状态信息,包括资源对象、集群配置、元数据…

基于SSM+小程序的旅游社交登录管理系统(旅游4)

👉文末查看项目功能视频演示获取源码sql脚本视频导入教程视频 1、项目介绍 ​ 本旅游社交小程序功能有管理员和用户。管理员有个人中心,用户管理,每日签到管理,景点推荐管理,景点分类管理,防疫查询管理&a…

51单片机完全学习——DS18B20温度传感器

一、DS18B20数据手册解读 首先我们知道DS18B20使用的是单总线传输,默认情况下读出来的温度是12位的,我们这里只讨论外部电源供电这种情况。 有这张图片我们知道,12位温度的最小分辨率是10^-4次方,因此就是0.0625.我们只需要将最后…

论文阅读(二十三):Squeeze-and-Excitation Networks

文章目录 1.介绍2.原理3.代码4.SE模块的应用 论文:Squeeze-and-Excitation Networks   论文链接:Squeeze-and-Excitation Networks   代码链接:Github 1.介绍 卷积算子使网络能够在每一层的局部感受野中融合空间(spatial&…

内容安全与系统构建加速,助力解决生成式AI时代的双重挑战

内容安全与系统构建加速,助力解决生成式AI时代的双重挑战 0. 前言1. PRCV 20241.1 大会简介1.2 生成式 Al 时代的内容安全与系统构建加速 2. 生成式 AI2.1 生成模型2.2 生成模型与判别模型的区别2.3 生成模型的发展 3. GAI 内容安全3.1 GAI 时代内容安全挑战3.2 图像…

Linux 进程间通信_匿名管道

1.程间通信目的 : 数据传输:一个进程需要将它的数据发送给另一个进程 资源共享:多个进程之间共享同样的资源。 通知事件:一个进程需要向另一个或一组进程发送消息,通知它(它们)发生了某种事件(如…