如何计算以多个字符条件为条件的行数?

How to count the number of row conditional to multiple character criteria?

我在 R 中有这样一个数据框:

ID     Type
---------------------------
1      Green-Red-Red-Green
2      Pink-Blue-Red-Red
3      Green-Green-Red
4      Pink-Blue-Blue-Green
5      Red-Red-Red-Green

所以,我想计算包含绿色和红色但不包含粉色和蓝色的行数。

在这种情况下,数字将是 3(3 行,实际上当 ID = 1,3 和 5 时)。

我找不到如何使用多个条件和字符来做到这一点。请问我该怎么做?

你可以做到

 `library(data.table)`  

 `dt <- as.data.table(data_frame) # transform your data frame to a data table 
  nrow(dt[(Type%like%"Green") & (Type%like%"Red" & !Type%like%"Pink") & 
 (Type%like%"Blue"),]) # & stands for AND, ! stands for NOT`

根据评论中的问题进行更新

这将为您提供 "Pink" 和 "Blue"

之间的字符数

string <- "Pink-Green-Blue-Red" tmp <- str_match(string, "Pink(.*?)Blue") nchar(tmp[,2]).

所以你可以

dt[,tmp:=str_match(Type, "Pink(.*?)Blue")]
nrow(dt[!is.na(tmp)])

你也可以玩正则表达式:

sum(grepl("Green", dt$Type) & grepl("Red", dt$Type) & !grepl("Pink", dt$Type) & !grepl("Blue", dt$Type))