我希望删除数据框中包含特定模式的行,并且如果可能的话,使用tidyverse语法。
我希望删除第一列包含“cat”并且col2:4中包含以下任何单词的行:dog,fox或cow。 对于此示例,这将从原始数据中删除行1和4。
这是一个样本数据集:
df <- data.frame(col1 = c("cat", "fox", "dog", "cat", "pig"),
col2 = c("lion", "tiger", "elephant", "dog", "cow"),
col3 = c("bird", "cow", "sheep", "fox", "dog"),
col4 = c("dog", "cat", "cat", "cow", "fox"))
我尝试了许多不同的方法,但经常遇到问题。这是我的最新尝试:
filtered_df <- df %>%
filter(!(animal1 == "cat" & !any(cowfoxdog <- across(animal2:animal4, ~ . %in% c("cow", "fox", "dog")))))
这会返回以下错误:
Error in `filter()`:
! Problem while computing `..1 = !...`.
Caused by error in `FUN()`:
! only defined on a data frame with all numeric variables
\(x)
是一种速记匿名函数(自R 4.1.0起)。\(x)x + 1
等同于function(x) x + 1
,以及tidyverse速记符号~ .x + 1
。你第二条评论中的版本应该可以工作。 - zephryl