給定一個小寫字串。前任:
s <- 'abcdefghijklmnopqrstuvwxyz'
目標是使字串中的所有其他元音都大寫。
此處所需的輸出:
abcdEfghijklmnOpqrstuvwxyz
如您所見,因為所有元音都按順序使用,e并且o大寫。
在所有情況下,字串中都只有小寫字符。
對于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。
uj5u.com熱心網友回復:
它不是單線,而是:
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取自這個問題;使用c(FALSE, TRUE)] 來自這里。)
uj5u.com熱心網友回復:
另一種可能的解決方案,使用stringr和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"
uj5u.com熱心網友回復:
使用gregexpr, then 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"
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/403643.html
標籤:
下一篇:縮短R中的長向量
