2011-06-03 52 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