[R] foreach package

1. foreach package

The foreach package provides a new looping construct for executing R code repeatedly. The main reason for using the foreach package is that it supports parallel execution

parameters to be introduced:

  • foreach: specify the variables to iterate over
  • %do%: binary operators, execute the R expression sequentially
  • %dopar%: binary operators, execute the R expression using the currently registered backend
  • %:%: nesting operators, create nested foreach loops

Usage:
foreach(..., .combine, .init, .final=NULL, .inorder=TRUE, .multicombine=FALSE, .maxcombine=if (.multicombine) 100 else 2, .errorhandling=c('stop', 'remove', 'pass'), .packages=NULL, .export=NULL, .noexport=NULL, .verbose=FALSE)

  • .combine: c is useful for concatenating the results into a vector; cbind and rbind can combine vectors into a matrix; + and * can be used to process numeric data. By default, the results are returned in a list.

2. Examples

> # foreach package
> 
> library(foreach)
> 
> foreach(i=1:3)%do% sqrt(i)
[[1]]
[1] 1

[[2]]
[1] 1.414214

[[3]]
[1] 1.732051

> foreach(i=1:3, .combine = "c")%do% sqrt(i)
[1] 1.000000 1.414214 1.732051
> foreach(i=1:3, .combine = "+")%do% sqrt(i)
[1] 4.146264
> foreach(i=1:3, .combine = "*")%do% sqrt(i)
[1] 2.44949
> 
> library(MASS)
> foreach(1:10, .combine = "rbind")%do% mvrnorm(1,rep(0,3), diag(3))
                [,1]        [,2]       [,3]
result.1   1.5630549  1.02659189  1.2804769
result.2  -1.6957373  0.67580662 -0.9537855
result.3  -2.0787570  0.51637372  0.7091263
result.4  -0.1867845 -0.06440223 -1.1717261
result.5   0.3833949 -0.59977010  0.3472026
result.6  -1.8356754  1.77720778  0.1851016
result.7   0.6922240 -0.90876651  0.3539157
result.8   1.1140055 -0.44083003 -1.3054194
result.9   0.5193093  0.34136464  1.7463392
result.10  0.9659776 -1.01835620  0.4123284

> foreach(i=1:3, .combine = "c")%:%
+   foreach(j=1:5, .combine="+")%do%{
+     rnorm(1)
+   }
[1] 0.8171045 5.3792075 1.3293824

reference:
https://cran.r-project.org/web/packages/foreach/vignettes/nested.pdf

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值