简体   繁体   English

不同长度向量列表中的匹配数

[英]Match number within list of different length vectors

I want to match a number within a list containing vector of different lengths. 我想匹配包含不同长度向量的列表中的数字。 Still my solution (below) doesn't match anything beyond the first item of each vector. 仍然我的解决方案(如下)与每个向量的第一项都不匹配。

seq_ <- seq(1:10)
list_ <- list(seq_[1:3], seq_[4:7], seq_[8:10])
list_ 
#  [[1]]
#  [1] 1 2 3
# 
#  [[2]]
#  [1] 4 5 6 7
# 
# [[3]]
#  [1]  8  9 10

but

for (i in seq_) {
  print(match(i,list_))
}
# [1] 1
# [1] NA
# [1] NA
# [1] 3
# [1] NA
# [1] NA
# [1] NA
# [1] NA
# [1] NA
# [1] NA

In the general case, you probably will be happier with which , as in 在一般情况下,您可能会更喜欢which ,例如

EDIT: rewrote to show the full looping over values. 编辑:重写以显示完整的循环值。

seq_ <- seq(1:10)
list_ <- list(seq_[1:3], seq_[4:7], seq_[8:10])
matchlist<-list(length=length(list_))
    for( j in 1:length(list_)) {
       matchlist[[j]] <-  unlist(sapply(seq_, function(k) which(list_[[j]]==k) ))
    }

That will return the locations of all matches. 这将返回所有匹配项的位置。 It's probably more clear what's happening if you create an input like my.list <- list(sample(1:10,4,replace=TRUE), sample(1:10,7,replace=TRUE)) 如果创建类似my.list <- list(sample(1:10,4,replace=TRUE), sample(1:10,7,replace=TRUE))的输入,可能更清楚了。 my.list <- list(sample(1:10,4,replace=TRUE), sample(1:10,7,replace=TRUE))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM