Meredith Hu Meredith Hu - 1 year ago 165
Python Question

R equivalent of [x[y] for x,y in zip(i,j)] in python?

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)


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] 2

[1] 4

[1] 2

You can also use mapply which returns a vector instead of a list:

mapply(`[`, i, j)
[1] 2 4 2
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download