使向量中的所有其他元音大写

Making every other vowel in a vector uppercase

给定一个小写字符串。例如:

s <- 'abcdefghijklmnopqrstuvwxyz'

目标是让字符串中的所有其他元音字母大写。

此处需要的输出:

abcdEfghijklmnOpqrstuvwxyz

如您所见,由于所有元音均按顺序使用,因此 eo 大写。

在所有情况下,字符串中只有小写字符。

对于aieou,期望的输出是:

aIeOu

我如何在 R 中执行此操作?

我试过了:

s[unlist(strsplit(s, '')) %in% c('a', 'e', 'i', 'o', 'u')] <- toupper(s[unlist(strsplit(s, '')) %in% c('a', 'e', 'i', 'o', 'u')])

但是没有用。

即使这行得通,也不会是所有其他元音

R 版本 4.1.1.

这不是单行,而是:

s <- 'abcdefghijklmnopqrstuvwxyz'

as_list <- unlist(strsplit(s, ''))
vowels <- as_list %in% c('a', 'e', 'i', 'o', 'u')
every_other_index <- which(vowels)[c(FALSE, TRUE)]

as_list[every_other_index] <- toupper(as_list[every_other_index])

print(paste(as_list, collapse=''))

给出:

[1] "abcdEfghijklmnOpqrstuvwxyz"

which 的使用取自 this question; use of c(FALSE, TRUE)] from here。)

使用 gregexpr,然后 gsub,使用 \U 大写字母模式替换。

f <- function(s, u=c('a', 'e', 'i', 'o', 'u')) {
  v <- sort(unlist(sapply(u, \(u) all(unlist(gregexpr(u, s)) > -1))))
  v <- v[seq_along(v) %% 2 == 0]
  gsub(sprintf('(%s)', paste(names(v[v]), collapse='|')), '\U\1', s, perl=TRUE)
}

f('abcdefghijklmnopqrstuvwxyz')
# [1] "abcdEfghijklmnOpqrstuvwxyz"

f('world hello')
# [1] "world hEllo"

f('hello world')
# [1] "hEllo world"

另一种可能的解决方案,使用 stringrpurrr::map2

library(tidyverse)

s <- 'abcdefghijklmnopqrstuvwxyz'

s %>% 
  str_split("") %>% unlist %>% 
  map2({1:nchar(s) %in% (str_which(.,"[aeiou]") %>% .[c(F,T)])},
       ~ if_else(.y, str_to_upper(.x),.x)) %>% 
  str_c(collapse = "")

#> [1] "abcdEfghijklmnOpqrstuvwxyz"