I am relatively new to R and cannot figure out how to turn my for
loop into a foreach
loop.
I have a vector of few elements, i.e.
> hpattern
[1] "sim0_pmax.tif" "sim0_vmax.tif" "sim1_pmax.tif" "sim1_vmax.tif"
> typeof(hpattern)
[1] "character"
First: I come from the python word, the hpattern
item should be a list, since it is created as follows
list_h30 = data.frame(list.files(path = tr30dir, pattern=paste(depthfile,". $",sep=""), recursive = TRUE, full.names = FALSE))
hpattern <- sub(paste(".*",depthfile,sep=""), "", list_h30[,1])
How come the typeof
hpattern
is character and not list?
Second: if I run
for (hpi in hpattern) {print(hpi)}
I get
[1] "sim0_pmax.tif"
[1] "sim0_vmax.tif"
[1] "sim1_pmax.tif"
[1] "sim1_vmax.tif"
if I run
foreach(hpi=hpattern, .combine='c') %do% {print(hpi)}
I get
[1] "sim0_pmax.tif"
[1] "sim0_vmax.tif"
[1] "sim1_pmax.tif"
[1] "sim1_vmax.tif"
[1] "sim0_pmax.tif" "sim0_vmax.tif" "sim1_pmax.tif" "sim1_vmax.tif"
I do not understand why I get the last output.
CodePudding user response:
As Roland said, sub
returns a character vector (in R
, most things are vectors). Another useful function to check your object is str
.
About foreach
: it combines the output of each execution of the loop. You've specified that you want a vector (by .combine = 'c'
).
As print
returns every object invisibly, each hpi
gets printed inside the loop and then combined to the final vector. Compare it to when you don't print it:
foreach(hpi=hpattern, .combine='c') %do% {hpi}
[1] "sim0_pmax.tif" "sim0_vmax.tif" "sim1_pmax.tif" "sim1_vmax.tif"