使用条件删除行

Delete rows using conditional

我有一个 data.frame 这样的:

Client Product   
1      VV_Brazil_Jul
2      VV_Brazil_Mar
5      VV_US_Jul
1      VV_JP_Apr
3      VV_CH_May
6      VV_Brazil_Aug

我想删除包含 "Brazil" 的所有行。

您可以使用 grepl 函数和 !查找不匹配的案例:

# Create a dataframe where some cases have the product with Brazil as part of the value
df <- structure(list(Client = c(1L, 2L, 5L, 1L, 3L, 6L), 
                     Product = c("VV_Brazil_Jul", "VV_Brazil_Mar", "VV_US_Jul", "VV_JP_Apr", "VV_CH_May", "VV_Brazil_Aug")), 
                row.names = c(NA, -6L), class = c("data.table", "data.frame"))

# Display the original dataframe in the Console
df

# Limit the dataframe to cases which do not have Brazil as part of the product
df <- df[!grepl("Brazil", df$Product, ignore.case = TRUE),]

# Display the revised dataframe in the Console
df

您可以对 tidyverse 集合做同样的事情

dplyr::slice(df, -stringr::str_which(df$Product, "Brazil"))