gpt4 book ai didi

r - 如何获得R中两个向量之间元素的第n个匹配?

转载 作者:行者123 更新时间:2023-12-04 11:18:08 24 4
gpt4 key购买 nike

match返回其第一个和第二个参数之间的第一个匹配项的位置:

match(c("a","c"), c("a", "a", "b", "c", "c", "c")) # 1 4

除了第一个之外,指定匹配项的最佳方法是什么?例如,我们想要 "a" 的第二个匹配项第三个是 "c" (所以我们会得到: 2 6 )。

更新:低效的解决方案进行 n 次查找:
value_index_query <- data.frame(value = c("a", "c"), index = c(2, 3))
id <- c("a", "a", "b", "c", "c", "c")
apply(value_index_query, 1, function(value_index) {
value <- value_index[1]
index <- as.integer(value_index[2])
which(id == value)[index]
})

最佳答案

这也使用 mapply 通过 which(.)[n] 操作串联运行两列。

with(value_index_query,  
mapply( function(target, nth) which(id==target)[nth],
target=value, nth=index) )
[1] 2 6

关于r - 如何获得R中两个向量之间元素的第n个匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34324076/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com