首页 > 解决方案 > 计算元音的问题,检查以单词中的元音开头或结尾

问题描述

考虑下面的代码来计算每个单词中字母“a”的出现次数:

data <- data.frame(number=1:4, string=c("this.is.a.great.word", "Education", "Earth.Is.Round", "Pinky), stringsAsFactors = F)

library(stringr)

data$Count_of_a <- str_count(data$string, "a")

data

这将导致这样的事情:

  number               string Count_of_a
1      1 this.is.a.great.word          2
2      2            Education          1
3      3       Earth.Is.Round          1
4      4       Pinky                   0

我试图做更多的事情:

  1. 计算每个单词中元音的总数
  2. 总数 每个单词中的字母
  3. 单词是否以元音开头,则为 1,否则为 0
  4. 单词是否以元音结尾,则为 1,否则为 0

问题是如果我使用 nchar(data$string),它也会计算点 '.' 我在上述 4 个要求上也找不到太多帮助。

我想看起来像这样的最终数据:

number    string                 starts_with_vowel   ends_with_vowel   TotalLtrs
1         this.is.a.great.word          0                 0             16
2         Education                     1                 0             9
3         Earth.Is.Round                1                 0             12
4         Pinky                         0                 1             5

标签: rregexdplyr

解决方案


您想要正则表达式的组合

library(tidyverse)
data %>%
  mutate(
    nvowels = str_count(tolower(string), "[aeoiu]"),
    total_letters = str_count(tolower(string), "\\w"),
    starts_with_vowel = grepl("^[aeiou]", tolower(string)),
    ends_with_vowel = grepl("[aeiou]$", tolower(string))
  )


# number               string nvowels total_letters starts_with_vowel ends_with_vowel
# 1      1 this.is.a.great.word       6            16             FALSE           FALSE
# 2      2            Education       5             9              TRUE           FALSE
# 3      3       Earth.Is.Round       5            12              TRUE           FALSE
# 4      4                Pinky       1             5             FALSE           FALSE

如果您考虑y元音,请像这样添加

nvowels = str_count(tolower(string), "[aeoiuy]")
starts_with_vowel = grepl("^[aeiouy]", tolower(string))
ends_with_vowel = grepl("[aeiouy]$", tolower(string))

推荐阅读