Trouble merging lists of different lengths generated from nested 'if' loop

Hard to give a specific without a proper reprex bec.ause the data would need to be reversed engineered and, you'll have heard, R is a lazy evaluation language, so I get stuck at

Error in transect : object 'transect' not found

So, let's approach it abstractly.

It's useful to think of R as school algebra—f(x)=y$ where the three objects (in R everything is an object) are x, what's at hand, y, what's desired and f some function to make the transformation. Any or all of these objects can be composite and often the solution is as simple as composing an f from {base} functions or other packages.

To begin, x is transect is a data frame with a multiple variables named colnames_i \dots colnames_n. The return, y will be a vector of those values in colname1 that are associated with those values in colname33 that have an absolute value < 10.

There's are two functions for that in the {dplyr} package—filter and %>% (like the bash pipe | operator).

I'm first going to introduce two convenience values

strandline <- transect[abs(transect$colname33 ) < 10)
westing <- min(transect$column33)
transect %>% filter(colname1 < strandline & column1 == westing ) %>%
select(colname1)  -> X #some new collector object

Programmers coming to R from C and its progeny bring unsuitable attachment to control flow, which is not R's strong suit. Anything that requires heavy lifting is best done in C/C++ or Python and brought into the session with {Rcpp} or {reticulate}.

The specific problem you found with only getting the last iteration is a common illustration. The fix for those times when only a loop will to is to create a receiver object of appropriate size outside the loop and write each i to it.

1 Like