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

conditional recoding column in R

my df looks like this containing one column

df <- c("1:a1_01_01","2:a2_03_03","3:a3_07_07")

I want to add two more columns in this dataframe by recoding existing column like following

column1: ("1:a1", "2:a2", "3:a3")
column2:("a1","a2","a3")

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

>Solution :

We can use trimws

library(dplyr)
df %>% 
   mutate(column1 =trimws(col1, whitespace = "_.*"),
         column2 = trimws(column1, whitespace = "\\d+:"))

data

df <- structure(list(col1 = c("1:a1_01_01", "2:a2_03_03", "3:a3_07_07"
)), class = "data.frame", row.names = c(NA, -3L))
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