r - 计算元音的问题,检查以单词中的元音开头或结尾
问题描述
考虑下面的代码来计算每个单词中字母“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,否则为 0
- 单词是否以元音结尾,则为 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
解决方案
您想要正则表达式的组合
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))
推荐阅读
- api - BONITA BPM 用户任务合约返回空数组
- google-chrome-extension - 增加或减少 url 参数的扩展
- scala - 将被拒绝的记录保存在另一个 rdd
- java - UDP:关于接收响应如何工作的问题
- c++ - istream 运算符跳过空格字符
- c++ - 从 Eigen 中的向量/矩阵中提取元素
- numpy - 用 complex64 进行 LU 分解的数值精度
- git - 用于搜索提交消息的 Git 别名
- javascript - LocalForage async/await getItem() 等待 2 个变量然后完成加载
- c# - 如何创建跨度
在类型 T 的单个变量(字段或 ref 参数)上长度为 1