[R] foreach package
2016-01-22 01:19
295 查看
foreach package
Examples
1.
The
parameters to be introduced:
Usage:
reference:
https://cran.r-project.org/web/packages/foreach/vignettes/nested.pdf
Examples
1. foreach
package
The foreachpackage provides a new looping construct for executing R code repeatedly. The main reason for using the
foreachpackage 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:
cis useful for concatenating the results into a vector;
cbindand
rbindcan 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
相关文章推荐
- C#中循环语句:while、for、foreach的使用
- PHP中foreach()用法汇总
- 深入解析php中的foreach问题
- 7个超级实用的PHP代码片段
- C#使用foreach遍历哈希表(hashtable)的方法
- C#中foreach语句使用break暂停遍历的方法
- Smarty Foreach 使用说明
- PHP实现通过get方式识别用户发送邮件的方法
- C#中foreach语句深入研究
- C#使用foreach语句搜索数组元素的方法
- C#使用foreach语句简单遍历数组的方法
- 利用浏览器的Javascript控制台调试PHP程序
- PHP中的函数-- foreach()的用法详解
- php foreach、while性能比较
- php循环语句 for()与foreach()用法区别介绍
- C#使用foreach语句遍历二维数组的方法
- PHP的foreach中使用引用时需要注意的一个问题和解决方法
- php中如何使对象可以像数组一样进行foreach循环
- php foreach正序倒序输出示例代码
- php下foreach提示Warning:Invalid argument supplied for foreach()的解决方法