【发布时间】:2020-12-22 17:43:40
【问题描述】:
我正在尝试在分组的 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,但这并不能解决我的问题,因为它会找到 any 出现指定字符串的组。
我还可以做一些单独的代码来识别 id,然后使用它来子集原始 df,如下所示:
ids <- df %>% group_by(id) %>% slice(2) %>% filter(string %in% "is") %>% select(id)
desired_df <- df %>% filter(id %in% ids$id)
但我想知道是否可以在单个管道系列中做一些更简单的事情。
帮助表示赞赏!
【问题讨论】: