Meredith Hu - 1 year ago 109

Python Question

I was wondering is there a R equivalent of this list comprehension of a duple in python? What it does is extract certain elements from a nested list i given indices from j:

`i = [[1,2,3],[2,3,4],[2,4,2]]`

j = [1,2,0]

whatineed = [x[y] for x,y in izip(i,j)]

Presumably, in R the corresponding i and j would be lists/vectors:

`i = list(c(1,2,3),c(2,3,4),c(2,4,2))`

j = c(2,3,1)

or

`j = list(2,3,1)`

Thank you so much for your help in advance!!

Answer Source

In R you use `Map`

function:

```
i = list(c(1,2,3),c(2,3,4),c(2,4,2))
j = c(2,3,1)
Map(`[`, i, j)
[[1]]
[1] 2
[[2]]
[1] 4
[[3]]
[1] 2
```

You can also use `mapply`

which returns a vector instead of a list:

```
mapply(`[`, i, j)
[1] 2 4 2
```