R中的apply族函数和多线程计算
一.apply族函数
1.apply 应用于矩阵和数组
# apply
# 1代表行,2代表列
# create a matrix of 10 rows x 2 columns
m <- matrix(c(1:10, 11:20), nrow = 10, ncol = 2)
# mean of the rows
apply(m, 1, mean)
[1] 6 7 8 9 10 11 12 13 14 15
# mean of the columns
apply(m, 2, mean)
[1] 5.5 15.5
# divide all values by 2
apply(m, 1:2, function(x) x/2)
2.eapply 应用于环境中的变量
# a new environment
e <- new.env()
# two environment variables, a and b
e$a <- 1:10
e$b <- 11:20
# mean of the variables
eapply(e, mean)
$b
[1] 15.5 $a
[1] 5.5
3.lapply应用于列表,返回列表,实际data.frame也是一种list,一种由多个长度相同的向量cbind一起的list:lapply(list, function)
sapply(iris[,1:4],mean)
Sepal.Length Sepal.Width Petal.Length Petal.Width
5.843333 3.057333 3.758000 1.199333 lapply(iris[,1:4],mean)
$Sepal.Length
[1] 5.843333 $Sepal.Width
[1] 3.057333 $Petal.Length
[1] 3.758 $Petal.Width
[1] 1.199333
4.sapply 是lapply的友好形式.lapply和sapply都可应用于list,data.frame。只是返回的对象类型不一样,前者是list,后者看情况,如果是每一个list下面的元素长度都一样,返回的结果就会被就会简化。举例说明。
# 下面两个返回的结果是一样一样的,都是list
sapply(iris,unique)
lapply(iris,unique) # 下面两个前者返回向量,后者返回list
sapply(iris[,1:4],mean)
lapply(iris[,1:4],mean) #下面两个前者返回data.frame,后者反回list
sapply(iris[,1:4], function(x) x/2)
lapply(iris[,1:4], function(x) x/2) # sapply会根据返回结果,选最合适的对象类型来存放对象,而list反悔的统统都是list
# 以下两者返回结果一样
library(magrittr)
lapply(iris[,1:4],mean)%>%unlist()
sapply(iris[,1:4],mean)
5.vapply要求提供第三个参数,即输出的格式
l <- list(a = 1:10, b = 11:20)
# fivenum of values using vapply
l.fivenum <- vapply(l, fivenum, c(Min.=0, "1st Qu."=0, Median=0, "3rd Qu."=0, Max.=0))
class(l.fivenum)
[1] "matrix"
# let's see it
l.fivenum
a b
Min. 1.0 11.0
1st Qu. 3.0 13.0
Median 5.5 15.5
3rd Qu. 8.0 18.0
Max. 10.0 20.0
6.replicate
Description: “replicate is a wrapper for the common use of sapply for repeated evaluation of an expression (which will usually involve random number generation).”
replicate(10, rnorm(10))
7.mapply可传递多个参数进去.
mapply is a multivariate version of sapply. mapply applies FUN to the first elements of each ... argument, the second elements, the third elements, and so on. Arguments are recycled if necessary.
l1 <- list(a = c(1:10), b = c(11:20))
l2 <- list(c = c(21:30), d = c(31:40))
# sum the corresponding elements of l1 and l2
mapply(sum, l1$a, l1$b, l2$c, l2$d)
[1] 64 68 72 76 80 84 88 92 96 100
#mapply像是可以传递多个参数的saply
mapply(rep, 1:4, 5)
[,1] [,2] [,3] [,4]
[1,] 1 2 3 4
[2,] 1 2 3 4
[3,] 1 2 3 4
[4,] 1 2 3 4
[5,] 1 2 3 4
8.rapply
Description: “rapply is a recursive version of lapply.”
# let's start with our usual simple list example
l <- list(a = 1:10, b = 11:20)
# log2 of each value in the list
rapply(l, log2)
a1 a2 a3 a4 a5 a6 a7 a8
0.000000 1.000000 1.584963 2.000000 2.321928 2.584963 2.807355 3.000000
a9 a10 b1 b2 b3 b4 b5 b6
3.169925 3.321928 3.459432 3.584963 3.700440 3.807355 3.906891 4.000000
b7 b8 b9 b10
4.087463 4.169925 4.247928 4.321928
# log2 of each value in each list
rapply(l, log2, how = "list")
$a
[1] 0.000000 1.000000 1.584963 2.000000 2.321928 2.584963 2.807355 3.000000
[9] 3.169925 3.321928 $b
[1] 3.459432 3.584963 3.700440 3.807355 3.906891 4.000000 4.087463 4.169925
[9] 4.247928 4.321928 # what if the function is the mean?
rapply(l, mean)
a b
5.5 15.5 rapply(l, mean, how = "list")
$a
[1] 5.5 $b
[1] 15.5
二.多线程计算
下面用欧拉问题14,来演示R中的向量化编程(利用apply组函数)和多线程
#-----Longest Collatz sequence Problem 14
func <- function(x) {
n = 1
raw <- x
while (x > 1) {
x <- ifelse(x%%2==0,x/2,3*x+1)
n = n + 1
}
return(c(raw,n))
} #方法1 向量化编程
library(magrittr)
system.time({
x <- 1:1e5
res1 <- sapply(x, func)%>%t()
}) 用户 系统 流逝
37.960 0.360 41.315 #方法2 向量化编程
system.time({
x <- 1:1e5
res2 <- do.call('rbind',lapply(x,func))
}) 用户 系统 流逝
36.031 0.181 36.769 #方法3 多线程计算
library(parallel)
# 用system.time来返回计算所需时间
system.time({
x <- 1:1e5
cl <- makeCluster(4) # 初始化四核心集群
results <- parLapply(cl,x,func) # lapply的并行版本
res.df <- do.call('rbind',results) # 整合结果
stopCluster(cl) # 关闭集群
}) 用户 系统 流逝
0.199 0.064 20.038 # 方法4 for 循环
system.time({
m <- matrix(nrow = 0,ncol = 2)
for(i in 1:1e5){
m <- rbind(m,func(i))
}
}) #方法4用时太长
以上。
参考:
A brief introduction to “apply” in R
R中的apply族函数和多线程计算的更多相关文章
- R中利用apply、tapply、lapply、sapply、mapply、table等函数进行分组统计
apply函数(对一个数组按行或者按列进行计算): 使用格式为: apply(X, MARGIN, FUN, ...) 其中X为一个数组:MARGIN为一个向量(表示要将函数FUN应用到X的行还是列) ...
- 总结——R中查看属性的函数
本文原创,转载注明出处,本人Q1273314690 R中知道一个变量的主要内容和结构,对我们编写代码是很重要的,也可以帮我们避免很多错误. 但是,R中有好几个关于属性查看的函数,我们往往不知道什么时候 ...
- R中的sub替换函数【转】
R中的grep.grepl.sub.gsub.regexpr.gregexpr等函数都使用正则表达式的规则进行匹配.默认是egrep的规则,也可以选用Perl语言的规则.在这里,我们以R中的sub函数 ...
- R中的数据重塑函数
1.去除重复数据 函数:duplicated(x, incomparables = FALSE, MARGIN = 1,fromLast = FALSE, ...),返回一个布尔值向量,重复数据的第一 ...
- R 中的do.call 函数
do.call 函数是一个高阶函数, 其第一个参数为一个函数名,或者匿名函数,第二个参数是一个list 对象, 其实是参数列表 比如读取文件test.txt, 内容为 read.table(input ...
- 在 R 中使用 Python 字符串函数
sprintf( )函数很强大,但并非适用于所有应用场景.例如,如果一些部分在模板中多次出现,那么就需要多次写一样的参数.这通常会使得代码冗长而且难以修改:sprintf("%s, %d y ...
- (1)apply族函数总论
来自为知笔记(Wiz) 附件列表
- R中的高效批量处理函数(lapply sapply apply tapply mapply)(转)
转自:http://blog.csdn.net/wa2003/article/details/45887055 R语言提供了批量处理函数,可以循环遍历某个集合内的所有或部分元素,以简化操作. 这些函数 ...
- R语言学习4:函数,流程控制,数据框重塑
本系列是一个新的系列,在此系列中,我将和大家共同学习R语言.由于我对R语言的了解也甚少,所以本系列更多以一个学习者的视角来完成. 参考教材:<R语言实战>第二版(Robert I.Kaba ...
随机推荐
- 图解源码之FutureTask篇(AQS应用)
所以,FutureTask既可以由Executor来调度执行,也可以由调度线程调用FutureTask.run()直接执行. FutureTask是通过AQS的模板设计模式来实现阻塞get方法的. 从 ...
- C# 进程通信-命名管道
之前看wcf服务的时候看到wcf有支持管道通信协议,之前不知道,最近刚好有用到这个,这里写个简单实例 .net有已经封装好的pip通信的对象NamedPipeServerStream 和NamedPi ...
- sdoi 2017 r1游记
第一次参加省选... 不过幸亏我参加过WC和THUWC,还是有些经验的. 经验就是:多拿部分分(不过话说我的部分分大部分都丢了). D1: 第一题没有预处理斐波那契数列的幂,算复杂度算错了...丢了4 ...
- LeetCode赛题----Find Left Most Element
问题描述 Given a binary tree, find the left most element in the last row of the tree. Example 1: Input: ...
- Windows下本机简易监控系统搭建(Telegraf+Influxdb+Grafana)
一.文件准备 1.1 文件名称 telegraf-1.2.1_windows_amd64.zip influxdb-1.2.2_windows_amd64.zip grafana-4.2.0.wind ...
- #include <unistd.h> 的作用
原文:http://blog.csdn.net/ybsun2010/article/details/24832113 由字面意思,unistd.h是unix std的意思,是POSIX标准定义的uni ...
- Flutter知识点:数据存储之sqflite
sqflite是一款轻量级的关系型数据库,类似SQLite. 在Flutter平台我们使用sqflite库来同时支持Android 和iOS. 使用介绍 1.首选需要在pubspec.yaml 导入库 ...
- Raspberry install wine
sudo apt install wine winecfg出现问题 树莓派3B是卡片电脑,内存为1GB,一般运行Linux.Linux两种主流的内存分配方法2G/2G和3G/1G,树莓派系统后期优化性 ...
- centos7安装go语言环境
安装包下载地址为:https://golang.org/dl/. 各个系统对应的包名: 解压安装 1.下载源码包:go1.7rc3.linux-amd64.tar.gz 2.将下载的源码包解压至 /u ...
- cache2go开源项目的回调方法使用
https://github.com/muesli/cache2go 结构体 type CacheTable struct { sync.RWMutex . name string items map ...