[英]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:假设我想向每个子列表添加第三个元素“field3”,并使用以下 sapply(..) 和父赋值运算符的组合来完成:
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?使用这个 sapply 语句而不是 for 循环是否有潜在的速度提升?
I tend to use for-loop
s in this context.在这种情况下,我倾向于使用for-loop
。 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.它更清晰并且sapply
不会加速 AFAIK,因为sapply
只是引擎盖下for-loop
一个特例。 See here for details.有关详细信息,请参见此处。
eg:例如:
for (i in s) a[[i]]$field3 <- 5 - i
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.