Question:
I have column names, for example they look like this20819830_r1ar_u_stationary
and 2081974_f8ar_u
. I am trying to get rid of the first set of numbers in the column names. I tried using this codenames(df)[1:2] <- gsub("^.*_","",names(df[,c(1:2)])) [/code]
but when I use this, the column names turn tostationary
and u
. I can see the code is removing everything up until the last _
how do I change the code so that it removes everything up until the first _
.Answer:
Instead of matching.*
– one or more characters as .
matches any characters, it should be one or more digits (\\d+
) from the start (^
) of the stringnames(df)[1:2] <- sub("^\\d+_", "", names(df)[1:2]) [/code]
If you have better answer, please add a comment about this, thank you!