Reputation: 65
I have a df
with column names of a.b.c.v1, d.e.f.v1, h.j.k.v1
, and would like to remove v1
from all the column names of df
.
I suppose I should use gsub
but my trials with that were not successful.
Upvotes: 2
Views: 3186
Reputation: 887971
We can use sub
to remove the .v1
from the end of the string. (If we only need to remove 'v1', just remove the \\.
from the pattern to match, but I think a .
at the end of column name may not look that good). Here, we match the dot (\\.
) followed by one of more characters that are not a dot ([^.]+
) until the end of the string ($
) and replace it with ""
.
colnames(df) <- sub('\\.[^.]+$', '', colnames(df))
colnames(df)
#[1] "a.b.c" "d.e.f" "h.j.k"
Upvotes: 4