[R] Creating data using multiple for loops

Jeff Newmiller jdnewm|| @end|ng |rom dcn@d@v|@@c@@u@
Tue Aug 20 00:02:36 CEST 2019

Perhaps different people find different concepts the most challenging, but I find looking at the output of expand.grid quite informative... do try it out.

The do.call function seems to be the more obscure function here, but Bert's code

id <- do.call( paste0, expand.grid(0:9,1:3,1:5) )

is equivalent to

all_comb <- expand.grid( 0:9, 1:3, 1:5 )
all_comb # look at it for learning, remove once you understand
paste0( all_comb[[1]], all_comb[[2]], all_comb[[3]] )

because all_comb is a data frame, which is a list of column vectors all the same length. The do.call function expects the first argument to be a function symbol, while the second argument to do.call should be a single object that is a list of arguments you want that function to be given as separate arguments. The paste0 function puts the three vectors together into one character vector, element by element.

Read the help pages for each function:

On the other hand, nested for loops seem to become spaghetti quickly in my mind... essentially just write-only code because I never want to look at it again.

On August 19, 2019 2:09:59 PM PDT, Jim Lemon <drjimlemon using gmail.com> wrote:
>Hi Greg,
>I replied because I thought the name of the "expand.grid" function can
>be puzzling. While "expand.grid" is a very elegant and useful
>function, it is much easier to see what is happening with explicit
>loops rather than loops buried deep inside "expand.grid". Also note
>Bill's comment about producing repeats by converting numeric values to
>character without the leading zeros. You can also use "formatC" to
>deal with that problem.
>On Tue, Aug 20, 2019 at 12:05 AM <g.eastham.gilbert using gmail.com> wrote:
>> Jim,
>> Thank you very much for your help. I have "unpacked" the code and
>have a rudimentary understanding of what you did. Thanks again.
>However, I have no idea to what Bert is referring. Could you help me
>understand his suggestion? Thanks.
>> -Greg
>R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
>PLEASE do read the posting guide
>and provide commented, minimal, self-contained, reproducible code.

Sent from my phone. Please excuse my brevity.

More information about the R-help mailing list