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:
我想知道是否有一个R等价于这个列表对python中的duple的理解?它所做的是从一个嵌套列表中提取特定的元素从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:
假设在R中,对应的i和j是列表/向量:
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!!
非常感谢您的帮助!!
1 个解决方案
#1
5
In R you use Map
function:
在R中使用Map函数:
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返回一个矢量而不是列表:
mapply(`[`, i, j)
[1] 2 4 2
#1
5
In R you use Map
function:
在R中使用Map函数:
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返回一个矢量而不是列表:
mapply(`[`, i, j)
[1] 2 4 2