一.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. 【SSH网上商城项目实战18】过滤器实现购物登录功能的判断

    转自:https://blog.csdn.net/eson_15/article/details/51425010 上一节我们做完了购物车的基本操作,但是有个问题是:当用户点击结算时,我们应该做一个登 ...

  2. Generator函数自执行

    Generator函数实现 function* gen(x){ var y = yield x + 2; return y } //1.调用g函数会返回一个内部的指针 var g = gen(1); ...

  3. RegExp对象的exec方法

    RegExp对象的exec方法和String对象的match方法用法十分相似,分两篇博客讲讲其各自的用法和它们之间的异同. 下一篇讨论match方法的用法和两者的异同. 定义及语法 [定义] exec ...

  4. 使用jQuery获取Dribbble的内容

    Introduction As a web developer, third party API integration is something you will have to face. Esp ...

  5. bootstrap学习笔记(网页开发小知识)

    这是我在学习Boostrap网页开发时遇到的主要知识点: 1.导航条navbar 添加.navbar-fixed-top类可以让导航条固定在顶部,固定的导航条会遮住页面上的其他内容,除非给<bo ...

  6. plan,idea,and dream

    自学机器学习/数据分析/前端 目前想法是从前端入手,学会写/分析网页及其内容/数据,然后使用爬虫爬取数据,然后用机器学习算法对数据进行处理.哈哈,想法是不是太天真了. 学习都从网上的资料入手,因此发现 ...

  7. GIS 地理坐标分类

    wgs84 GPS系统直接通过卫星定位获得的坐标.(最基础的坐标.) gcj02 兲朝已安全原因为由,要求在中国使用的地图产品使用的都必须是加密后的坐标.这套加密后的坐标就是gcj02 google的 ...

  8. MAVLink Linux/QNX/MacOs Integration Tutorial (UDP)

    MAVLink Linux/QNX/MacOs Integration Tutorial (UDP) Overview This program was written to test the udp ...

  9. Python Basics

    廖雪峰老师博客 1. 可变参数(例如 *nums),允许传入一个list 或 tuple,但是 关键字参数(例如 **kv),允许传入一个dict,具体可参考此页: 2. set与dict类似,但只是 ...

  10. mysql免安装版配置+navicat测试

    好久之前就在mysql官网下载了mysql的包,但是一直没有安装.今天测试下. 下载好的mysql是一个zip压缩包,直接解压就可以了,然后改名为mysql,以免路径太复杂. 配置环境变量 把D:\A ...