r - 选择包含特定值的行的组(使用 dplyr 和管道)

标签 r filter dplyr group-by

我正在尝试选择分组 df 中的组,这些组在每个组内的特定行上包含特定字符串。

考虑以下 df:

df <- data.frame(id = c(rep("id_1", 4),
                        rep("id_2", 4),
                        rep("id_3", 4)),
                 string = c("here",
                            "is", 
                            "some",
                            "text",
                            "here",
                            "is",
                            "other",
                            "text",
                            "there",
                            "are",
                            "final",
                            "texts"))

我想创建一个数据框,其中仅包含第二行包含“is”一词的组。

这是一些不正确的代码:

desired_df <- df %>% group_by(id) %>% 
        filter(slice(select(., string), 2) %in% "is")

这是所需的输出:

desired_df <- data.frame(id = c(rep("id_1", 4),
                                      rep("id_2", 4)),
                               string = c("here",
                                          "is", 
                                          "some",
                                          "text",
                                          "here",
                                          "is",
                                          "other",
                                          "text"))

我看过here但这并不能解决我的问题,因为这会找到出现任意指定字符串的组。

我还可以执行某种单独的代码,在其中识别 ids,然后使用它来对原始 df 进行子集化,如下所示:

ids <- df %>% group_by(id) %>% slice(2) %>% filter(string %in% "is") %>% select(id)
desired_df <- df %>% filter(id %in% ids$id)

但我想知道是否可以在单个管道系列中做一些更简单的事情。

感谢帮助!

最佳答案

按“id”分组后,对第二个元素的“string”进行子集化,并在 %in% 的左侧应用带有“is”的 %in% 来每组返回一个 TRUE

library(dplyr)
df %>%
    group_by(id) %>% 
    filter('is' %in% string[2]) %>%
    ungroup

-输出

# A tibble: 8 x 2
#  id    string
#  <chr> <chr> 
#1 id_1  here  
#2 id_1  is    
#3 id_1  some  
#4 id_1  text  
#5 id_2  here  
#6 id_2  is    
#7 id_2  other 
#8 id_2  text  

关于r - 选择包含特定值的行的组(使用 dplyr 和管道),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65413356/

相关文章:

r - 在函数中复制数据框

r - 错误概率函数

r - gganimate 根据时间对多条路径进行动画处理

php - 是 LIKE,但 int 表示应检查的字符串

r - R中基于多列的匹配数据框

r - 在管道中使用 dplyr 中的 group_by() 和 predict.lm 和 do() 进行年份线性外推

r - ggplot2 中的小时刻度

python - 将过滤器函数转换为Python代码

google-sheets - 如何计算在 Google 表格的列中只出现一次(和多次)的值的数量?

r - 模糊与精确匹配相结合