简体   繁体   中英

Nested foreach loop seq() output in r

Consider the following code:

space<- 2
years<- 4

year<- foreach(1:years, .combine = rbind)%:%
  foreach(1:space, .combine = rbind)%do% seq(1:years)

year

         [,1] [,2] [,3] [,4]
result.1    1    2    3    4
result.2    1    2    3    4
result.1    1    2    3    4
result.2    1    2    3    4
result.1    1    2    3    4
result.2    1    2    3    4
result.1    1    2    3    4
result.2    1    2    3    4

Why is it returning the output as an int[1:8, 1:4] ? The output I am looking for should be int[1:8, 1] and look like this:

         [,1] 
result.1    1 
result.2    1 
result.1    2 
result.2    2 
result.1    3 
result.2    3 
result.1    4 
result.2    4 

The reason I want it to return something in this format is that I am performing many other nested foreach loops which are dependant on the iterators of space and year and space needs to be recorded as result.n .

Any help is greatly appreciated.

You return seq(1:years) for each combination (4x2 = 8) of two (unnamed) sequences.

To get the result you want, you need

year <- foreach(year = 1:years, .combine = rbind) %:%
  foreach(1:space, .combine = rbind) %do% year

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM