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

Removing all text before a certain character for all variables in R

I need to remove all text before the last "/" in a variable’s name for every variable in a data frame.

suppose this is the data frame:

/98519/name   aa77nf4/color   4//342/year
letters       blue            1995
letters       red             1997

I am looking for a command that can simplify this to

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

name        color     year
letters     blue      1995
letters     red       1997

>Solution :

We can use trimws with whitespace as a regex to match characters (.*) till the /

names(df1) <- trimws(names(df1), whitespace = ".*/")

Or another option is basename

names(df1) <- basename(names(df1))

-output

> df1
     name color year
1 letters  blue 1995
2 letters   red 1997

data

df1 <- structure(list(`/98519/name` = c("letters", "letters"), 
`aa77nf4/color` = c("blue", 
"red"), `4//342/year` = c(1995L, 1997L)), class = "data.frame", row.names = c(NA, 
-2L))
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