vendredi 14 mai 2021

R Return N characters from String based on If function for same string in R

I've built a data frame in R which contains a load of ICD-10 Diagnosis categories. They all consist of one letter then three numbers. What I'd like to do is create a new column based on these conditions: If the letter in string-position #1 = C or D, return the letter AND the first digit (string-position 2), else return only the first letter.

So i'd want my output to look like this:

ICD10 <- c("A123","B123","C123","D123", "E123")
return <- c("A","B","C1","D1","E")
df <- data.frame(ICD10, shortcd)

I've used the substr function with a start = 1, stop = 2 to trim all observations to 2 characters but I can't figure out how to make it conditional. i also tried dabbling with grep but couldn't get this doing anything! Any ideas / steers greatly appreciated!

Aucun commentaire:

Enregistrer un commentaire