我正在尝试删除数据中带有特定字符的行。在这种情况下,我试图删除*和-(但只有在相邻有多个破折号的情况下,即第6行)。我正在寻找的解决方案要么完全删除第4行和第6行,要么将它们更改为NA。我已经尝试过grepl、gsub和replace,但是有些东西不能正常工作。
下面是dataframe的示例。
df <-structure(list(text = c("1", "3", "5", "HR*", "12-2", "--")), class = "data.frame", row.names = c(NA,
-6L))这是我们想要的结果。
df <-structure(list(text = c("1", "3", "5", "12-2")), class = "data.frame", row.names = c(NA,
-4L))发布于 2022-08-05 15:52:58
如果您使用过grepl而没有运气,这可能是由于转义(*是regex中的一个特殊字符)或drop造成的。这行得通吗?
df <- df[!grepl("\\*|--", df$text), , drop=FALSE]
> df
text
1 1
2 3
3 5
5 12-2发布于 2022-08-05 15:34:30
我们可以使用str_detect
library(dplyr)
library(stringr)
df %>%
filter(str_detect(text, '\\d+'))或者是特定于字符*和--的
df %>%
filter(str_detect(text, "--|[*]", negate = TRUE))https://stackoverflow.com/questions/73252131
复制相似问题