6

Given a lower case string. Ex:

s <- 'abcdefghijklmnopqrstuvwxyz'

The goal is to make every other vowel in the string an uppercase.

Desired output here:

abcdEfghijklmnOpqrstuvwxyz

As you can see, since all vowels where used in order, e and o where uppercase.

There are only lowercase characters in the strings in all cases.

For aieou, the desired output is:

aIeOu

How could I do this in R?

I tried:

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

But no avail.

Even if this worked, it wouldn't be every other vowel

R version 4.1.1.

user438383
  • 4,338
  • 6
  • 23
  • 35
U12-Forward
  • 65,118
  • 12
  • 70
  • 89

3 Answers3

5

It's not a one-liner, but:

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=''))

gives:

[1] "abcdEfghijklmnOpqrstuvwxyz"

(Use of which taken from this question; use of c(FALSE, TRUE)] from here.)

Joe
  • 26,561
  • 11
  • 64
  • 84
2

Another possible solution, using stringr and purrr::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"
PaulS
  • 10,636
  • 1
  • 7
  • 20
  • It doesn't do it on every **other** vowel. – U12-Forward Jan 04 '22 at 12:38
  • 1
    Thanks, @U12-Forward, for calling my attention to that. I had misread your original question -- missed the part every _other_... I am going to adapt my solution to comply with that. – PaulS Jan 04 '22 at 12:43
  • 1
    My new edited solution accomplishes what you are looking for, @U12-Forward. – PaulS Jan 04 '22 at 13:08
1

Using gregexpr, then gsub, with \\Uppercase pattern replacement.

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"
jay.sf
  • 46,523
  • 6
  • 46
  • 87