2

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.

zx8754
  • 52,746
  • 12
  • 114
  • 209
HoHoHo
  • 65
  • 1
  • 10
  • 1
    Please read the info about [how to ask a good question](http://stackoverflow.com/help/how-to-ask) and how to give a [reproducible example](http://stackoverflow.com/questions/5963269). This will make it much easier for others to help you. – zx8754 Mar 23 '16 at 12:21
  • Also, add your code even if it didn't work, it might help to clarify your problem. – zx8754 Mar 23 '16 at 12:22

1 Answers1

4

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"
akrun
  • 874,273
  • 37
  • 540
  • 662
  • yes, it works but it returns only list of of column names with removed v1. but i would like to preserve df structure. – HoHoHo Mar 23 '16 at 11:02
  • @Olga Sorry, I am not sure I understand your comment. This remove the end of the string with `.v1`. How is this changing the structure of 'df' as we are only dealing with column name? – akrun Mar 23 '16 at 11:03
  • yes, but it returns character vector containing column names with removed v1 – HoHoHo Mar 23 '16 at 11:03
  • 3
    check out your data.frame. The names should have changed – Sotos Mar 23 '16 at 11:05
  • @Olga As I understand the question, you want to remove the substring .v1 from the column names. This does what you mentioned in the post. – akrun Mar 23 '16 at 11:08
  • 1
    @Olga, check head(df), this code definitely removes the '.v1' from the names of the data frame columns – Sam Mar 23 '16 at 13:58