这也使用mapply通过哪个(.)[n]操作串联运行两列.
with(value_index_query, mapply( function(target, nth) which(id==target)[nth], target=value, nth=index) ) [1] 2 6
这是一个data.table解决方案,我们将id
向量与映射表连接起来.然后我们可以.EACHI
用于分组,index
从.I
每个组中抓取.
library(data.table) ## 'dti' would be your 'value_index_query' with the 'value' column renamed dti <- data.table(id = c("a", "c"), index = c(2, 3)) ## join it with 'id' and take 'index' by group data.table(id)[dti, .I[index], by = .EACHI, on = "id"]$V1 # [1] 2 6
我们可以把它放到一个函数中:
viq <- function(id, value, index) { dti <- data.table(id = value, index = index) data.table(id)[dti, .I[index], by = .EACHI, on = "id"]$V1 } id <- c("a", "a", "b", "c", "c", "c") viq(id, c("a", "c"), 2:3) # [1] 2 6 viq(id, c("a", "c"), c(2, 4)) # [1] 2 NA viq(id, c("a", "b", "c"), c(2, 1, 4)) # [1] 2 3 NA viq(id, c("a", "b", "c"), c(2, 1, 3)) # [1] 2 3 6