Zip or enumerate in R?
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 do for(i in 1:length(mylist)){...}
):
> mylist <- list('a'=10,'b'=20,'c'=30)
> for (i in seq_along(mylist)){
+ print(paste(i,names(mylist)[i],mylist[[i]]))
+ }
[1] "1 a 10"
[1] "2 b 20"
[1] "3 c 30"
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:
> x <- 1:3
> y <- 4:6
> data.frame(x=x, y=y)
x y
1 1 4
2 2 5
3 3 6
There have been some discussions around list comprehension for R, e.g. here or there. The hash package even offers dictionary-like structure. However, as others said, it is difficult to try to map one language facilities onto another (even if this is what Comparison of programming languages actually offers) without a clear understanding of what it is supposed to be used to. For example, I can mimic Python zip()
in R as follows:
Python
In [1]: x = [1,2,3]
In [2]: y = [4,5,6]
In [3]: zip(x, y)
Out[3]: [(1, 4), (2, 5), (3, 6)]
R
> x <- 1:3
> y <- 4:6
> list(x, y) # gives a simple list
> as.list(paste(x, y)) # three tuples, as a list of characters
> mapply(list, x, y, SIMPLIFY=F) # gives a list of 3 tuples
> rbind(x, y) # gives a 2x3 matrix
As can be seen, this really depends on what you want to do with the result afterwards.
zip
and enumerate
are not particularly difficult to implement in R:
#' zip(1:5,1:10)
zip <- function(...) {
mapply(list, ..., SIMPLIFY = FALSE)
}
Enumerate is simple to define in terms of zip
:
#' enumerate(l=LETTERS)
enumerate <- function(...) {
zip(ix=seq_along(..1), ...)
}
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.