What are the R equivalents for these Python list comprehensions:
[(i,j) for i,j in zip(index, Values)]
[(i,j) for i,j in enumerate(Values)]
[(i,j) for i,j in enumerate(range(10,20))] %MWE, indexing or enumerating to
%keep up with the index, there may
%be some parameter to look this up
Example with Output
>>> [(i,j) for i,j in enumerate(range(10,20))]
[(0, 10), (1, 11), (2, 12), (3, 13), (4, 14), (5, 15), (6, 16), (7, 17), (8, 18), (9, 19)]
I have solved this problem earlier with some trick in R but cannot remember anymore, the first idea was itertools -pkg but I am hoping to find a more idiomatic way of doing things.
If that is the Python print representation of a matrix, then this code:
You are still leaving those of us who are not Python users in the dark regarding the structure of your desired output. You use the term "list" but the output suggests an ordered set of tuples.
Given @chi's guidance we might also suggest using the very R-centric 'dataframe' structure
... which has the flexibility of a list in terms of column types and the access features of a matrix in terms of row and column indexing. Or one could use hhh's request and create the implicitly indexed values of the j-vector,
10:20
, using therownames
vector that starts at "1" by default, but which could be altered to become a character vector starting at "0"Unfortunately, the unwary will find that dfrm[0, ] is not a happy call, returning vector of length 0.
Answer for python
enumerate
:In R, a list is ordered (see this answer). Thus, all you need is to index either keys (using
names()[i]
) or values (using[[i]]
).Using
seq_along
(alternatively can dofor(i in 1:length(mylist)){...}
):Answer for python
zip
:See one of the above answers to mimic the list of tuples. My preference is towards a data frame as shown in BondedDust's answer:
In order to use Python style list comprehensions with enumerations, such as enumerated lists, one way is to install List-comprehension package
LC
(developed 2018) and itertools package (developed 2015).List comprehensions in R
You can find the
LC
package here.Example
where the programming syntax is not yet as clean and polished as in Python but functionally working and its help outlines:
where notice that you can leave the predicates empty for example in the above example.
Python-style itertools and enumerations
You can use R's itertools that is very similar to Python's itertools, further in Cran here
where described
Example. enumeration
Example. enumeration with ZIP
zip
andenumerate
are not particularly difficult to implement in R:Enumerate is simple to define in terms of
zip
:Since these are proper functions, we can use
...
to make them fairly flexible and terse, and take advantage of mapply's behavior, such as recycling inputs and naming output correctly.Another option which will create a list of vectors is to use the Map function as seen here by @peterhurford: https://rdrr.io/github/peterhurford/funtools/src/R/zippers.R