我有一个看起来像这样的数据集:
s <- c("car, car, car, toy, toy", "toy", "horse, horse", "car, horse")
如果我grep("car", s)
,我将可以得到[1] 1 4
如果我想获得频率,我可以做length(grep("car", s))
但是,我想知道是否有可能获得返回元素内部和元素之间模式频率的结果?
例如预期结果将如下所示:
[1] 1 1 1 4
和/或
$`car, car, car, toy, toy`
[1] 3
$toy
[1] 0
$`horse, hores`
[1] 0
$`car, horse`
[1] 1
和/或
$`car, car, car, toy, toy`
[1] 3
$`car, horse`
[1] 1
和/或
[[1]]
[1] 3
[[4]]
[1] 1
您的回答受到赞赏。非常感谢你!
答案 0 :(得分:3)
The stringr
package does this with str_count
.
stringr::str_count(s, "car")
# [1] 3 0 0 1