1

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?

Anton
  • 365
  • 2
  • 12

1 Answers1

1

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
symbolrush
  • 7,123
  • 1
  • 39
  • 67
  • Interesting, I thought one of the points of the *apply function family was to allow parallellization better than for-loops. Is the only benefit of *apply syntactical brevity? – Anton Apr 25 '19 at 08:12
  • @Anton: I added a link to a discussion on apply-functions and speed, see my edit – symbolrush Apr 25 '19 at 08:18
  • Thank you, excellent reference for speed discussions, which there seem to be a lot of now that I looked. Also, linked at top of that question is [this](http://adv-r.had.co.nz/Functionals.html) where Hadley points out a few cases where for-loops are recommended over *apply family, including one similar to the one I asked about. – Anton Apr 25 '19 at 11:07