简体   繁体   English

如何根据条件和字符串删除行?

[英]How to remove rows based on both condition and string?

I require to remove rows based on a string and a numeric value.我需要根据字符串和数值删除行。 In this case, a comment string and ID = 1在这种情况下, comment字符串和 ID = 1

My dataset我的数据集

ID  Value 
1   commentmg/l
1   32 mg/l
2   154 mg/ml
1   commentmg/l
3   54 u/l
8   1 l

Desired output期望输出

ID  Value 
1   32 mg/l
2   154 mg/ml
3   54 u/l
8   1 l

So far im able to remove all the comment by using到目前为止,我可以通过使用删除所有comment

df = df %>%  
  filter(!grepl('comment', Value ))

But im requiring to add an extra condition based on ID但是我需要根据 ID 添加一个额外的条件

ADDENDUM: the filter idea works but will only keep the rows with other ID's附录:过滤器的想法有效,但只会保留具有其他 ID 的行

We can use我们可以用

library(dplyr)
library(stringr)
df %>% 
    filter(!(str_detect(Value, 'comment') & ID == 1))

-outut -输出

ID     Value
1  1   32 mg/l
2  2 154 mg/ml
3  3    54 u/l
4  8       1 l

data数据

df <- structure(list(ID = c(1L, 1L, 2L, 1L, 3L, 8L), Value = c("commentmg/l", 
"32 mg/l", "154 mg/ml", "commentmg/l", "54 u/l", "1 l")), 
class = "data.frame", row.names = c(NA, 
-6L))

What about & ID == 1 ? & ID == 1怎么样?

> df %>%
+     filter(!(ID == 1 & grepl("comment", Value)))
  ID     Value
1  1   32 mg/l
2  2 154 mg/ml
3  3    54 u/l
4  8       1 l

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM