简体   繁体   中英

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?

I tend to use for-loop s 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.

eg:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM