Using regexp to select rows in R dataframe

前端 未结 7 1123
终归单人心
终归单人心 2020-12-08 00:48

I\'m trying to select rows in a dataframe where the string contained in a column matches either a regular expression or a substring:

dataframe:

7条回答
  •  情书的邮戳
    2020-12-08 01:45

    subset(dat, grepl("ADN", bName)  &  pName == "2011-02-10_R2" )
    

    Note "&" (and not "&&" which is not vectorized) and that "==" (and not"=" which is assignment).

    Note that you could have used:

     dat[ with(dat,  grepl("ADN", bName)  &  pName == "2011-02-10_R2" ) , ]
    

    ... and that might be preferable when used inside functions, however, that will return NA values for any lines where dat$pName is NA. That defect (which some regard as a feature) could be removed by the addition of & !is.na(dat$pName) to the logical expression.

提交回复
热议问题