←
PDF 236 / 520 Typically, however, your strings will be one column of a data frame, and you'll want to use filt
→
English · PDF 236
Original PDF page 236
中文 · PDF 236

然而,通常你的字符串会是数据框中的一列,你会想要使用 filter 而不是:

df <- tibble(
  word = words,
  i = seq_along(word)
)
df %>%
  filter(str_detect(words, "x$"))
#> # A tibble: 4 x 2
#>   word    i
#>   <chr> <int>
#> 1   box   108
#> 2   sex   747
#> 3   six   772
#> 4   tax   841

的一个变体是 str_detect() :它不是简单地给出是或否,而是告诉你一个字符串中有多少个匹配: str_count()很自然地可以将

x <- c("apple", "banana", "pear")
str_count(x, "a")
#> [1] 1 3 1# On average, how many vowels per word?
mean(str_count(words, "[aeiou]"))
#> [1] 1.99

与 str_count() abababa mutate():

df %>%
  mutate(
    vowels = str_count(word, "[aeiou]"),
    consonants = str_count(word, "[^aeiou]")
)
#> # A tibble: 980 x 4
#>     word    i vowels consonants
#>     <chr> <int> <int>      <int>
#> 1       a      1      1      0
#> 2     able   2      2      2
#> 3     about   3      3      2
#> 4     absolute   4      4      4
#> 5     accept    5      2      4
#> 6     account    6      3      4
#> # ... with 974 more rows

一起使用