Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iteratively adding elements to list in one step

Tags:

r

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.

like image 650
shadow Avatar asked Mar 02 '15 11:03

shadow


People also ask

Can we add element in list while iterating?

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.

Can you add to a list while iterating Python?

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.

Can you add to an ArrayList while iterating?

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.

How do you modify a list while iterating?

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.


2 Answers

Here's another way

rev(within(list(), { a = 1; b = 2; c = b }))
# $a
# [1] 1
# 
# $b
# [1] 2
# 
# $c
# [1] 2
like image 184
lukeA Avatar answered Nov 15 '22 04:11

lukeA


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
like image 31
shadow Avatar answered Nov 15 '22 05:11

shadow