Analysis in R: “foreach” package useful for iterative processing

RAnalytics
スポンサーリンク

The “for” and “apply” commands are useful for iterative processing, but they are sometimes inflexible. Here is a package that solves such problems.

Package version is 1.5.2. Checked with R version 4.2.2.

スポンサーリンク

Install Package

Run the following command.

#Install Package
install.packages("foreach")

Example

See the command and package help for details.

#Loading the library
library("foreach")

#Repeat a number of times:foreach command
foreach(i = 1:3) %do% rnorm(4)
[[1]]
[1] -1.2070657  0.2774292  1.0844412 -2.3456977

[[2]]
[1]  0.4291247  0.5060559 -0.5747400 -0.5466319

[[3]]
[1] -0.5644520 -0.8900378 -0.4771927 -0.9983864

#Output Settings:.combine option
#"c"を設定
foreach(i = 1:3, .combine = "c") %do% rnorm(4)
[1]  0.20610310 -0.98109899  0.02649167  1.59199127 -0.18092395 -0.06898068
[7] -0.41337942  1.16898955 -0.07810419 -0.84305630  0.29913439  2.08036405

#"cbind" option
foreach(i = 1:3, .combine = "cbind") %do% rnorm(4)
       result.1   result.2   result.3
[1,] -0.7236902 -0.5324504  1.3881262
[2,]  0.7675323 -0.8125667  0.4483272
[3,] -0.6613460  0.2139257 -0.5543930
[4,]  0.4193643  0.6085379 -1.9703620

#"rbind" option
foreach(i = 1:3, .combine = "rbind") %do% rnorm(4)
          [,1]      [,2]         [,3]       [,4]
result.1 -0.007604756 1.7770844 -1.138607737  1.3678272
result.2  1.329564791 0.3364728  0.006892838 -0.4554687
result.3 -0.366523933 0.6482866  2.070270861 -0.1533984

#Set "+";Sum the results of the calculations
foreach(i = 1:3, .combine = "+") %do% sum(i + 4)
[1] 18

#Set "*";Multiply the results of the calculations
foreach(i = 1:3, .combine = "*") %do% sum(i + 4)
[1] 210

#You can also create arrays like this
foreach(a = 11:14, .combine = "cbind") %:%
  foreach(b = 21:24, .combine = "c") %do%
  {
    sum(a, b)
  }
     result.1 result.2 result.3 result.4
[1,]       32       33       34       35
[2,]       33       34       35       36
[3,]       34       35       36       37
[4,]       35       36       37       38

#Use "when" command in the middle
#Add the value of b to a only if a is even
foreach(a = 11:14, .combine = "cbind") %:%
  foreach(b = 21:24, .combine = "c") %:%
  when(0 == a%%2) %do%
  {
    sum(a, b)
  }
     result.2 result.4
[1,]       33       35
[2,]       34       36
[3,]       35       37
[4,]       36       38

I hope this makes your analysis a little easier !!

Copied title and URL