Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace characters in a string using conditional formatting R

Tags:

r

I have a word list as in wordlist below:

 wordlist <- data.frame(words = c("anywhere", "youll", "feel", "comfortable", "please", "dont"))

I have another dataframe with a list of consonants:

 consonants <- data.frame(consonants = c("b", "c", "d", "f", "g", "h"))

I want to create a new variable in wordlist called word_structure, where all consonants are replaced with "C", and all vowels with "V":

 wordlist$word_structure <- c("VCCCCVCV", "CVVCC", "CVVC", "CVCCVCCVCCV", "CCVVCV", "CVCC")

I can't work out how to combine conditional formatting with gsub to get what I need.

like image 619
Catherine Laing Avatar asked Sep 02 '26 17:09

Catherine Laing


1 Answers

This seems a better fit for chartr() than 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
like image 154
Ritchie Sacramento Avatar answered Sep 04 '26 05:09

Ritchie Sacramento