我有一个数据框,其中“ 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")
在每个字符串中,我要提取出现在单词work
前面的单词。 work
可以出现多次,并且每次都需要提取或计算前面的单词。
最终,我想计算一下整个df中work
之前哪个单词出现的频率。
我尝试过的事情:
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分为几列。因此,也许另一种方法更合适。
非常感谢您的帮助!
答案 0 :(得分:2)
您可以将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
答案 1 :(得分:2)
首先,使用稍小的数据集以使其更容易跟踪代码的结果:
d = data.frame(id = 1:3, leg = c("home",
"work, R, eat, work",
"eat, work, R, work"), stringsAsFactors = FALSE)
在strsplit
上分割字符串(", "
)。循环搜索结果列表(lapply
)。获取“工作”的索引(which(x == "work")
),获取上一个索引(-1
)。如果“ work”是第一个单词,请使用pmax
获取空向量。索引单词(x[<the-index>]
。取消列出和计数项目(table(unlist(...
)。
table(unlist(lapply(strsplit(d$leg, ", "), function(x) x[pmax(0, which(x == "work") - 1)])))
# eat R
# 2 1
鉴于“ 最终,我有兴趣计算在整个df上哪个单词出现之前的频率。”,看来分组是不必要的。
答案 2 :(得分:1)
library(stringr)
WantedStrings <- sub(", work","",str_extract_all(df$leg_activity, "\\w+, work",simplify=T))
WantedStrings <- WantedStrings[WantedStrings != ""]
table(WantedStrings)
WantedStrings
car pt walk
5 2 2
答案 3 :(得分:1)
R基地一号班轮:
table(unlist(strsplit(gsub("(\\w+\\,)\\s*(work\\,)", "\\1",
lst$leg_activity), ", ")))