bricevk
bricevk

Reputation: 207

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

name        color     year
letters     blue      1995
letters     red       1997

Upvotes: 1

Views: 405

Answers (1)

akrun
akrun

Reputation: 887038

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))

Upvotes: 1

Related Questions