I am noticing this behavior of foreach
and print
in R. foreach somehow repeats the elements, but assigning result to variable "rectify" it.
> for (i in 1:3) {print(i+1)}
[1] 2
[1] 3
[1] 4
> foreach (i=1:3) %do% {print(i+1)}
[1] 2
[1] 3
[1] 4
[[1]]
[1] 2
[[2]]
[1] 3
[[3]]
[1] 4
> x<-foreach (i=1:3) %do% {print(i+1)}
[1] 2
[1] 3
[1] 4
> x
[[1]]
[1] 2
[[2]]
[1] 3
[[3]]
[1] 4
> foreach (i=1:3, .combine=c) %do% {print(i+1)}
[1] 2
[1] 3
[1] 4
[1] 2 3 4
> foreach (i=1:3) %do% {(i+1)}
[[1]]
[1] 2
[[2]]
[1] 3
[[3]]
[1] 4
> x <-foreach (i=1:3) %do% {(i+1)}
> x
[[1]]
[1] 2
[[2]]
[1] 3
[[3]]
[1] 4
> x<-for (i in 1:3) {(i+1)}
> x
NULL
Moreover, that brings me to the last test with simple for
. for
loop does not output results while foreach
does.
If I would want to pick up results from for clause, is there another dedicated way rather than
> x <- NULL
> for (i in 1:3) {x <- cbind(x,(i+1))}
> x
[,1] [,2] [,3]
[1,] 2 3 4