[英]returning the index of vector for a match
我有一个数据框,其中第一列是我要与之匹配的变量的名称。 此列具有797个观察值,并且是字符类型。 我有另一个向量也是字符类型,有31行。 我想返回与小字符向量匹配的数据帧(具有787个观测值)的列的索引。
我使用for循环尝试了一些代码。 但无法得到我想要的
vec_list<-vector()
for (i in inter_2004_05[,1]){
for(j in 1:nrow(test_t)){
if(inter_2004_05[i,1]=test_t[j]){
vec_list[i]= i
}
}
}
现在``是我要匹配的单词的向量。 我期望的是,我们应该检查数据帧第一列( inter_2004_05[,1]
)中的每个元素在字符向量( test_t
)中是否匹配。 我想要索引inter_2004_05[, 1]
在test_t
找到匹配test_t
这可以通过使用%in%和which完成。
inter_2004_05 = c('A','B','C','D')
test_t = c('C','B')
indices = which(inter_2004_05 %in% test_t)
正如RAB已经指出的那样, match
将返回索引,因此您可以立即使用这些索引来子集所需的内容。 我刚刚测试了以下示例:
#Create 2 vectors
word_vector <- c(paste("test", 1:50, sep=""))
test_vector <- c(paste("test", 10:15, sep=""))
#Find the index of every match
matches <- match(word_vector, test_vector)
#Now matches can be used to subset
word_vector2 <- word_vector[matches > 0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.