【问题标题】:Eliminate dataframe rows that match a character string消除与字符串匹配的数据框行
【发布时间】:2016-01-18 14:39:12
【问题描述】:

我有一个数据框rawdata,其中的列包含生态信息。我正在尝试消除列LatinName 与我已经拥有一些数据的物种向量匹配的所有行,并创建一个仅包含缺少数据的物种的新数据框。所以,我想做的是:

matches <- c("Thunnus thynnus", "Balaenoptera musculus", "Homarus americanus") 
# obviously these are a random subset; the real vector has ~16,000 values 
rawdata_missing <- rawdata %>% filter(LatinName != "matches") 

这不起作用,因为布尔运算符不能应用于字符串。或者我可以这样做:

rawdata_missing <- filter(rawdata, !grepl(matches, LatinName) 

这也不起作用,因为!grepl 也不能使用字符串。

我知道有很多方法可以使用LatinNamematches 中的行来对rawdata 进行子集化,但我想不出一个巧妙的方法来对rawdata 进行子集化,这样LatinName不在matches 中。

提前感谢您的帮助!

【问题讨论】:

  • 只需否定 %in% 运算符 - rawdata %&gt;% filter(!(LatinName %in% matches))
  • @thelatemail 的方法是这里的方法。但是为了将来参考,如果您确实需要将字符串向量转换为greplgrep 可以使用的正则表达式,您可以这样做,例如match.string = paste(matches, collapse="|")
  • @thelatemail 太完美了!谢谢你。我只是不知道如何写取反操作。

标签: r filter subset dplyr grepl


【解决方案1】:
filteredData <- rawdata[!(rawdata$LatinName %in% Matches), ]

【讨论】:

  • 谢谢!如上所示,这与否定 %in% 一样有效:)
【解决方案2】:

使用子集、粘贴、mapply 和 grepl 的另一种方式是......

fileteredData &lt;- subset(rawdata,mapply(grepl,rawdata$LatinName,paste(Matches,collapse = "|")) == FALSE)

【讨论】:

    猜你喜欢
    • 2011-10-02
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    • 2011-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-21
    相关资源
    最近更新 更多