Search code examples
rassignsapply

R: Parent assignment operator in sapply


Consider the two level list created by following code:

a = list()
s = seq(1,5)
for (i in s) {
  a[[i]] = list(field1 = i, field2 = letters[i])
}

Say I want to add a third element, "field3" to each sub-list, and do it with following combination of sapply(..) and the parent assignment operator:

sapply(s, function(x) a[[x]]$field3 <<- 5 - x)

Is this dangerous or considered abuse of the parent assignment operator? What is the recommended alternative? Are there potential speed gains from using this sapply statement instead of a for-loop?


Solution

  • I tend to use for-loops in this context. It's clearer and sapply does not speed it up AFAIK, since sapply is just a special case of a for-loop under the hood. See here for details.

    e.g.:

    for (i in s) a[[i]]$field3 <- 5 - i