R mapply两个列表元素明智

时间:2016-04-27 23:33:20

标签: r list apply

我有2个清单。一个列表提供如下索引:

dd[1:3]
[[1]]
[1]  2  5  6  7  9 14 16

[[2]]
[1] 5

[[3]]
integer(0)

第二个列表包含字符串:

ee[1:3]
[[1]]
 [1] "HP"     "A"   "HP"     "HP"    
 [5] "BD"  "A"   "A"   "NY"
 [9] "U"          "HP"     "HP"     "HP"    
[13] "HP"     "S"        "HP"     ""       
[17] "0"            

[[2]]
[1] "HP"  "HP"  "HP"  "HP"  "T"
[6] "HP"  "HP"  "0"         

[[3]]
[1] "HP" "HP" "0"

我想将列表dd中的索引应用于ee的相应元素,例如从ee[[1]][1]中选择2个,5个,6个,7个,9个,14个,16个元素,然后计算唯一元素的长度。我希望以矢量化方式进行,因为列表很大。

我知道这是mapply的一个简单应用,我错过了一些明显的东西。任何帮助是极大的赞赏。谢谢!

数据

dd <- list(c(2,  5,  6,  7,  9, 14, 16), 5, integer(0))
ee <- list(c("HP", "A", "HP", "HP", "BD", "A", "A", "NY", "U", "HP", 
             "HP", "HP", "HP", "S", "HP", "", "0"),
           c("HP", "HP", "HP", "HP", "T", "HP", "HP", "0"), c("HP", "HP", "0"))

2 个答案:

答案 0 :(得分:2)

您可以使用mapply以这种方式执行此操作:

HandleError

答案 1 :(得分:1)

另一种选择是使用list循环一个lapply的序列,基于另一个的索引子集并获取元素的频率

lapply(seq_along(ee), function(i) table(ee[[i]][dd[[i]]]))