【问题标题】:Checking Multiple Conditions检查多个条件
【发布时间】:2011-06-03 20:09:11
【问题描述】:

我有一个数据框,想知道某个字符串是否存在。 我想知道 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]。

救命!

【问题讨论】:

  • inscompany 分配也应该在测试之前进行。您是在寻找完全匹配还是部分匹配?在您的示例中,您有“庇护所”。这与 Shelter Insurance Company 相匹配吗?
  • 我只是在寻找部分匹配项?所以“Shelter”应该匹配“Shelter Insurance Company”

标签: r if-statement dataframe


【解决方案1】:

你想要%in%。这是一个例子:

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()函数相关,详见帮助页面。

【讨论】:

    【解决方案2】:

    我认为match%in% 不适用于部分匹配。 grepl 根据是否包含目标字符串给出逻辑(真/假)结果;我使用^ 仅在字符串开头强制匹配(您可能不需要)。需要anysapply 才能扩展到多对多匹配。如果您只想知道 任何 个字符串是否匹配,则需要在整个过程中再添加一个 any

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

    【讨论】:

      猜你喜欢
      • 2021-10-02
      • 1970-01-01
      • 2017-10-20
      • 1970-01-01
      • 2018-06-07
      • 2020-05-12
      • 1970-01-01
      • 2016-05-18
      • 2015-04-26
      相关资源
      最近更新 更多