首页 > 解决方案 > 如何提取字符串中某个单词之前的单词?

问题描述

我有一个数据框,其中“leg_activity”列的每一行都是一串逗号分隔的单词:

structure(list(id = c("100", "100060", "100073", "100098", "100102", 
"100104", "100125", "100128", "100149", "100217", "100220", "100271", 
"100464", "100465", "100520", "100607", "100653", "100745", "100757", 
"100760"), leg_activity = c("home", "home, car, work, car, leisure, car, other, car, leisure, car, work, car, shop, car, home", 
"home, walk, leisure, walk, leisure, walk, home", "home, car, other, car, shop, car, other, car, home", 
"home, car, work, car, home, car, home", "home", "home, walk, education, walk, home", 
"home, car, other, car, work, car, shop, car, shop, car, home", 
"home, car, shop, car, work, car, home", "home, bike, leisure, bike, home", 
"home, walk, shop, walk, home", "home, pt, leisure, car, leisure, pt, home", 
"home, car, education, car, home", "home, car, leisure, car, home", 
"home, walk, home, walk, shop, walk, home", "home, pt, work, walk, leisure, walk, work, pt, home", 
"home, pt, leisure, walk, leisure, walk, home", "home, walk, home, bike, shop, bike, home", 
"home, pt, work, pt, home, walk, work, walk, home", "home")), row.names = c(2L, 
15L, 20L, 24L, 31L, 33L, 40L, 43L, 48L, 70L, 73L, 93L, 147L, 
148L, 156L, 174L, 188L, 213L, 214L, 220L), class = "data.frame")

在每个字符串中,我想提取出现在 word 之前的单词workwork可以出现多次,每次都需要提取或统计前面的单词。

最终,我有兴趣计算work在整个 df 中哪个单词出现的频率。

我试过的:

library(dplyr)
library(stringr)

df%>%
  separate_rows(leg_activity, sep = "work, ") %>%
  group_by(id) %>%
  mutate(n = row_number()) %>%
  pivot_wider(names_from = n, values_from = leg_activity) 

显然,这不会导致结果,而只会将 df 分成列。所以也许另一种方法更合适。

非常感谢您的帮助!

标签: rstringdplyrstringr

解决方案


您可以separate_rows仅使用逗号将您的单词放在不同的行上。然后,在按您分组后,id您可以filter在以下/前导行具有“工作”的行吗?

library(dplyr)

df %>%
  separate_rows(leg_activity, sep = ",") %>%
  mutate(leg_activity = trimws(leg_activity)) %>%
  group_by(id) %>%
  filter(lead(leg_activity) == "work") %>%
  summarise(count = n())

输出

# A tibble: 6 x 2
  id     count
  <chr>  <int>
1 100060     2
2 100102     1
3 100128     1
4 100149     1
5 100607     2
6 100757     2

推荐阅读