Count number of strings 'within' 一个字符串作为 dplyr 链的一部分

Count number of strings 'within' a string as part of a dplyr chain

我有一个看起来像这样的数据框:

mydf <- data.frame(
  x = 1:3,
  y = c('apples; pears', 'oranges; bananas; grapes', 'apples')
)

mydf
  x                        y
1 1            apples; pears
2 2 oranges; bananas; grapes
3 3                   apples

我想在新变量 z 中计算水果的数量。期望的结果:

mydf
  x                        y z
1 1            apples; pears 2
2 2 oranges; bananas; grapes 3
3 3                   apples 1

尝试过:

mydf %>% mutate(z = str_split(y, ';') %>% length) # gives '3' for all fields

如何通过拆分某些字符(在本例中为“;”)来获取字符串中的字符串数?

可以用str_count

来完成
library(dplyr)
library(stringr0
mydf %>%
    mutate(z = str_count(y, '\w+'))

str_split的输出是一个listlength是整个列表的length,我们需要lengths(returns 每个 list 元素的 length)

mydf %>% 
   mutate(z = str_split(y, ';') %>% 
              lengths)
  x                        y z
1 1            apples; pears 2
2 2 oranges; bananas; grapes 3
3 3                   apples 1