一.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. java map常用的4种遍历方法

    public static void main(String[] args) { Map<String, String> map = new HashMap<String, Stri ...

  2. POJ 2524(并查集)

    这道题多了一个检查是否包含所有元素 可以设一个cnt表示集合里的数量,再与外面比较 #include <cstdio> #include <iostream> #include ...

  3. K:求取数组中最大连续子序列和的四个算法

    相关介绍:  求取数组中最大连续子序列和问题,是一个较为"古老"的一个问题.该问题的描述为,给定一个整型数组(当然浮点型也是可以的啦),求取其下标连续的子序列,且其和为该数组的所有 ...

  4. Mac(OS X)中Git安装与GitHub基本使用

    GitHub是一个面向开源及私有软件项目的托管平台.开源代码库以及版本控制系统,因为只支持 Git 作为唯一的版本库格式进行托管,故名 GitHub.通常在Windows下使用GitHub的教程是非常 ...

  5. async await的使用

    var sleep = function (time) { return new Promise(function (resolve, reject) { setTimeout(function () ...

  6. tensorflow梯度下降

    import numpy as np import tensorflow as tf import matplotlib.pyplot as plt num_points = 1000 vectors ...

  7. 探索canvas画布绘制技术

    图片来自KrzysztofBanaś 下面我们开始尝试研究不同的绘图风格和技术 - 边缘平滑,贝塞尔曲线,墨水和粉笔,笔和印章和图案 -等等.事实证明,网上没有太多关于此的内容.在下面的示例中,您请大 ...

  8. SQL-字符串运算符和函数

    COALESCE(columnname,string) 函数 将 NULL 值作为字符串(用空字符串或其他字符串替换 NULL)- 接受一列输入值(字段)如果该字段为 NULL,则返回后面替换的字符串 ...

  9. Linux / mysql: is it safe to copy mysql db files with cp command from one db to another?

    Copying is very simple for MyISAM and completely 100% risky (near suicidal) with InnoDB. From your q ...

  10. Unihan(统汉字)常用字段介绍

    0 背景 1 文件 1.1 IRG Sources 1.2 Dictionary Indices 1.3 Dictionary-like Data 1.4 Other Mappings 1.5 Rad ...