使用条件格式 R 替换字符串中的字符

Cat*_*ing 6 r

我有一个单词列表如下wordlist

 wordlist <- data.frame(words = c("anywhere", "youll", "feel", "comfortable", "please", "dont"))
Run Code Online (Sandbox Code Playgroud)

我有另一个包含辅音列表的数据框:

 consonants <- data.frame(consonants = c("b", "c", "d", "f", "g", "h"))
Run Code Online (Sandbox Code Playgroud)

我想在wordlistcalled中创建一个新变量word_structure,其中所有辅音都替换为"C",所有元音替换为"V"

 wordlist$word_structure <- c("VCCCCVCV", "CVVCC", "CVVC", "CVCCVCCVCCV", "CCVVCV", "CVCC")
Run Code Online (Sandbox Code Playgroud)

我不知道如何结合条件格式来gsub获得我需要的东西。

H 1*_*H 1 7

chartr()这似乎比以下更适合gsub()

vowels <- c("a", "e", "i", "o", "u")
consonants <- letters[!letters %in% vowels]

wordlist$word_structure <- chartr(
  old = paste(c(vowels, consonants), collapse = ""),
  new = paste(c(rep("V", 5), rep("C", 21)), collapse = ""), 
  wordlist$words)

wordlist

        words word_structure
1    anywhere       VCCCCVCV
2       youll          CVVCC
3        feel           CVVC
4 comfortable    CVCCVCCVCCV
5      please         CCVVCV
6        dont           CVCC
Run Code Online (Sandbox Code Playgroud)


xx0*_*020 1

与 @ stefan所示类似,在您的情况下,您可以写:

\n
library(tidyverse)\n\ndat <- tibble(\n  words = c("anywhere", "youll", "feel", "comfortable", "please", "dont"),\n  you_want = c("VCCCCVCV", "CVVCC", "CVVC", "CVCCVCCVCCV", "CCVVCV", "CVCC"),\n  you_get = str_replace_all(str_replace_all(words, "[aeiou]", "V"), "[^V]", "C")\n)\n\n## A tibble: 6 \xc3\x97 3\n#  words       you_want    you_get    \n#  <chr>       <chr>       <chr>      \n#1 anywhere    VCCCCVCV    VCCCCVCV   \n#2 youll       CVVCC       CVVCC      \n#3 feel        CVVC        CVVC       \n#4 comfortable CVCCVCCVCCV CVCCVCCVCCV\n#5 please      CCVVCV      CCVVCV     \n#6 dont        CVCC        CVCC   \n
Run Code Online (Sandbox Code Playgroud)\n