Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I detect a word in a column variable and mutate it in a new column in R using dplyr?

I have a data frame that looks like this :

var
A_CAT
B_DOG
A_CAT
F_HORSE
GEORGE_DOG
HeLeN_CAT

and I want to look like this :

var var_new
A_CAT CAT
B_DOG DOG
A_CAT CAT
F_HORSE HORSE
GEORGE_DOG DOG
HeLeN_CAT CAT

How can I do this in R ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

library(tidyverse)
var = c("A_CAT","B_DOG","A_CAT","F_HORSE","GEORGE_DOG","HeLeN_CAT")
df = tibble(var);df

>Solution :

df %>%
   mutate(var_new = str_remove(var, '.+_'))

# A tibble: 6 × 2
  var        var_new
  <chr>      <chr>  
1 A_CAT      CAT    
2 B_DOG      DOG    
3 A_CAT      CAT    
4 F_HORSE    HORSE  
5 GEORGE_DOG DOG    
6 HeLeN_CAT  CAT    
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading