Search code examples
rlistfor-loopiterationcomparison

How to make paired comparison for elements in one list


I have a list with four models as you could see and I am supposed to compare:

enter image description here

  1. the first one with the second one
  2. the second one with the third one
  3. the third one with the last

Thus I have proceeded with the following code, by creating a list for paired comparison:

comparison = vector('list', length = 3)
list_comparison = list(c(1,2), c(2,3), c(3,4)) 

for (i in list_comparison){
  comparison[i] = summary(compareFit(models[[i[1]]], models[[i[2]]]))
}

But the way I cannot stop the loop to remake twice the last comparison (3 vs 4) and in the list, I find twice with the same results.

length(comparison)
[1] 4

How is that possible? How could be the index improved? Could you suggest some alternatives if there is no solution?

Thanks


Solution

  • It is just that the comparison assignment index is based on the value of the list_comparison which is a vector. Instead, loop over the sequence of the list, thus the output can be assigned to each element of the initiated list 'comparison'

    for(i in seq_along(list_comparison))
    {
    tmp <- list_comparison[[i]]
    comparison[[i]] <- summary(compareFit(models[[tmp[1]]], 
             models[[tmp[2]]]))
    }
    

    Instead of initiating a list and assign, we could also loop over the list directly with lapply

    comparison <- lapply(list_comparison, function(x)
                    summary(compareFit(models[[x[1]]],
                              models[[x[2]]]))
            )