一.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

用Parallel和foreach包玩转并行计算

R中的apply族函数和多线程计算的更多相关文章

  1. R中利用apply、tapply、lapply、sapply、mapply、table等函数进行分组统计

    apply函数(对一个数组按行或者按列进行计算): 使用格式为: apply(X, MARGIN, FUN, ...) 其中X为一个数组:MARGIN为一个向量(表示要将函数FUN应用到X的行还是列) ...

  2. 总结——R中查看属性的函数

    本文原创,转载注明出处,本人Q1273314690 R中知道一个变量的主要内容和结构,对我们编写代码是很重要的,也可以帮我们避免很多错误. 但是,R中有好几个关于属性查看的函数,我们往往不知道什么时候 ...

  3. R中的sub替换函数【转】

    R中的grep.grepl.sub.gsub.regexpr.gregexpr等函数都使用正则表达式的规则进行匹配.默认是egrep的规则,也可以选用Perl语言的规则.在这里,我们以R中的sub函数 ...

  4. R中的数据重塑函数

    1.去除重复数据 函数:duplicated(x, incomparables = FALSE, MARGIN = 1,fromLast = FALSE, ...),返回一个布尔值向量,重复数据的第一 ...

  5. R 中的do.call 函数

    do.call 函数是一个高阶函数, 其第一个参数为一个函数名,或者匿名函数,第二个参数是一个list 对象, 其实是参数列表 比如读取文件test.txt, 内容为 read.table(input ...

  6. 在 R 中使用 Python 字符串函数

    sprintf( )函数很强大,但并非适用于所有应用场景.例如,如果一些部分在模板中多次出现,那么就需要多次写一样的参数.这通常会使得代码冗长而且难以修改:sprintf("%s, %d y ...

  7. (1)apply族函数总论

                  来自为知笔记(Wiz) 附件列表

  8. R中的高效批量处理函数(lapply sapply apply tapply mapply)(转)

    转自:http://blog.csdn.net/wa2003/article/details/45887055 R语言提供了批量处理函数,可以循环遍历某个集合内的所有或部分元素,以简化操作. 这些函数 ...

  9. R语言学习4:函数,流程控制,数据框重塑

    本系列是一个新的系列,在此系列中,我将和大家共同学习R语言.由于我对R语言的了解也甚少,所以本系列更多以一个学习者的视角来完成. 参考教材:<R语言实战>第二版(Robert I.Kaba ...

随机推荐

  1. jenkins学习笔记

    Jenkins 是一款流行的开源持续集成(Continuous Integration)工具,广泛用于项目开发,具有自动化构建.测试和部署等功能.本系列博客以 windows 10 环境为例 1 安装 ...

  2. PowerDesigner16导出SQL时如何添加注释

    添加注释方法 https://jingyan.baidu.com/article/47a29f24652e44c0142399c3.html 重点是修改value的值 alter table [%QU ...

  3. js延迟加载优化页面响应速度

    网页打开速度是衡量网站性能的一个极为重要的指标,今天就来说说如何通过JS延迟加载的方式提高页面响应速度: JS延迟加载的 含义:即等页面加载完成之后再加载 JavaScript 文件.作用:JS延迟加 ...

  4. HEOI2017 游记

    你若安好,便是晴天. …… 人就像命运下的蝼蚁,谁也无法操控自己的人生. ——阮行止 …… Day 0 中午就要出发了,上午教练还搞了一场欢乐信心赛,然而还是挂惨了.T3是bzoj的原题,但是当时写的 ...

  5. 理解webpack4.splitChunks之chunks

    上回说到按照默认的splitChunks配置,入口里面的第三方依赖没有打包出来,这个是因为chunks属性的原因,下面我们就介绍chunks属性的意义和用法. chunks的含义是拆分模块的范围,它有 ...

  6. background-position为什么会出现负值?

    上篇文章讲到了雪碧图,其中小机器人抖腿的动作设置了图片的background-position:-640px 循环到-1200px,那么这个数值是如何得出来的?下面具体分析一下如何计算backgrou ...

  7. php 生成唯一id的几种解决方法(实例)

    php 生成唯一id,网上查了下,有很多的方法 1.md5(time() . mt_rand(1,1000000)); 这种方法有一定的概率会出现重复 2.php内置函数uniqid() uniqid ...

  8. CentOS6.5(1)----设置静态IP并禁用IPV6

    使用vim命令编辑 /etc/sysconfig/network-scripts/ifcfg-eth0 文件 vim /etc/sysconfig/network-scripts/ifcfg-eth0 ...

  9. LeetCode算法题5----Longest Palindromic Substring

    #5. Longest Palindromic Substring Given a string S, find the longest palindromic substring in S. You ...

  10. Forword与sendRedirect的区别

    二.本质区别 解释一 一句话,转发是服务器行为,重定向是客户端行为.为什么这样说呢,这就要看两个动作的工作流程: 转发过程:客户浏览器发送http请求——>web服务器接受此请求——>调用 ...