2011-06-03 104 views
1

我有一个数据框,并想知道某个字符串是否存在。 我想知道df [,1]中的任何值是否包含inscompany中的任何值。检查多个条件

df = data.frame(company=c("KMart", "Shelter"), var2=c(5,7)) 
if(df[,1] == inscompany) print("YES") 
inscompany <- c("21st Century Auto Insurance", "AAA Auto Insurance", "AARP Auto Insurance", 
     "Allstate Auto Insurance", "American Family Auto Insurance", "Eastwood Auto Insurance", 
     "Erie Auto Insurance", "Farmers Auto Insurance", "GMAC Auto Insurance", "Hartford Auto Insurance", 
     "Infinity Auto Insurance", "Mercury Auto Insurance", "Nationwide Auto Insurance", "Progressive Auto Insurance", 
     "Shelter Insurance Company", "Titan Auto Insurance", "Travelers Auto Insurance", "USAA Auto Insurance") 

我得到一个错误消息,它只能检查inscompany的第一个值到df [,1]。

帮助!

+0

insan assignement也应该在测试前发生。你是否在寻找完全匹配,甚至是部分?在你的例子中你有“避难所”。这与Shelter保险公司相匹配吗? – Benjamin 2011-06-03 20:18:04

+0

我只是寻找部分匹配?所以“住房”应该与“住房保险公司”相匹配 – ATMathew 2011-06-03 21:08:57

回答

6

您想要%in%。下面是一个exampe:

R> chk <- c("A", "B", "Z") # some text 
R> chk %in% LETTERS[1:13]  # check for presence in first half of alphabet 
[1] TRUE TRUE FALSE 
R> 

match()功能相关,请参阅帮助页面了解详情。

1

我认为match%in%不适用于部分匹配。 grepl根据是否包含目标字符串给出逻辑(TRUE/FALSE)结果;我使用^仅在字符串的开头执行匹配(您可能不需要)。需要anysapply才能扩展到多对多的匹配。如果你只是想知道是否有任何的字符串匹配,那么在整个事情上你需要多一个any

sapply(df$company,function(x) any(grepl(paste("^",x,sep=""),inscompany))) 
[1] FALSE TRUE