[R] For loop with multiple iteration indexes

Berry, Charles ccberry @end|ng |rom uc@d@edu
Mon Sep 10 17:29:50 CEST 2018

I have a sense of deja vu:


There is some good advice there.

> On Sep 9, 2018, at 3:49 PM, David Disabato <ddisab01 using gmail.com> wrote:
> Hi R-help,
> I am trying to create a for loop with multiple iteration indexes. I don't
> want to use two different for loops nested together because I don't need
> the full matrix of the two indexes, just the diagonal elements (e.g., i[1]
> & j[1] and i[2] & j[2], but not i[1] & j[2]). Is there a way to specify
> both i and j in a single for loop? Here is a simplified example of
> pseudo-code where x and y are equally sized character vectors with column
> names and dat is their dataframe (obviously this code doesn't run in R, but
> hopefully you perceive my goal):
> r <- list()
> n <- 0
> for (i in x; j in y) {
>   n <- n + 1
>   r[[n]] <- cor(x = dat[, i], y = dat[, j])
> }
> print(r)
> I realize there are other solutions to this particular correlation example,
> but my actual problem is much more complicated, so I am hoping for a
> solution that generalizes across any code within the for loop.

A more aRtful way (than a for loop) to approach this is with mapply:

i <- head(colnames(mtcars))
j <- tail(colnames(mtcars))

r <- mapply(function(i, j, dat) cor( x = dat[, i], y = dat[, j]),
       i=i , j=j , MoreArgs = list( dat = mtcars), 

and if you want, maybe USE.NAMES = paste(i, j, sep="_")


More information about the R-help mailing list