I would like to add list elements iteratively in R, so that later elements can use the elements created earlier. The desired behavior is as follows:
lst <- list(a = 1,
b = 2,
c = b)
lst
## $a
## [1] 1
##
## $b
## [1] 2
##
## $c
## [1] 2
I know that I can easily accomplish the same using e.g.
lst <- list(a = 1,
b = 2)
lst[['c']] <- lst[['b']]
But I was wondering, if I could do this in one step.
You can't modify a Collection while iterating over it using an Iterator , except for Iterator. remove() . This will work except when the list starts iteration empty, in which case there will be no previous element. If that's a problem, you'll have to maintain a flag of some sort to indicate this edge case.
Use list. append() to append elements to a list while iterating over the list. Call len(obj) to get the length of the list obj . Use the syntax for i in range(stop) with stop as the previous result to iterate over the list.
ArrayList listIterator() – Add/RemoveListIterator supports to add and remove elements in the list while we are iterating over it. listIterator. add(Element e) – The element is inserted immediately before the element that would be returned by next() or after the element that would be returned previous() method.
The list. copy method returns a shallow copy of the object on which the method was called. This is necessary because we aren't allowed to modify a list's contents while iterating over it. However, we can iterate over a copy of the list and modify the contents of the original list.
Here's another way
rev(within(list(), { a = 1; b = 2; c = b }))
# $a
# [1] 1
#
# $b
# [1] 2
#
# $c
# [1] 2
Update: This is now possible with the lst
function of the tibble
package:
tibble::lst(a = 1, b = 2, c = b)
## $a
## [1] 1
##
## $b
## [1] 2
##
## $c
## [1] 2
My previous workaround was using mutate
from plyr
:
mylist <- function(...) plyr::mutate(.data=list(), ...)
mylist(a = 1,
b = 2,
c = b)
## $a
## [1] 1
##
## $b
## [1] 2
##
## $c
## [1] 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With