Search code examples
rrenamecol

Update column name unless it exists in other vector


I want to add something on the end of all column names in a dataframe, unless the column name exists in another given vector.

For example say I have

df <- data.frame('my' = c(1,2,3),
                 'data' = c(4,5,6),
                 'is' = c(7,8,9),
                 'here' = c(10,11,12))
dont_update <- c('my', 'is')
to_add <- '_new'

And I want to end up with

  my data_new is here_new
1  1        4  7       10
2  2        5  8       11
3  3        6  9       12

Solution

  • A bit verbose, but this works

    to_update <- names(df)[!names(df) %in% dont_update]
    names(df)[match(to_update, names(df))] <- paste0(to_update, to_add)
    

    or maybe this is clearer

    names(df) <- ifelse(names(df) %in% dont_update, names(df), paste0(names(df), to_add))