更新列名,除非它存在于其他向量中

Update column name unless it exists in other vector

我想在数据框中所有列名的末尾添加一些内容,除非该列名存在于另一个给定向量中。

比如说我有

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'

我想以

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

有点冗长,但这行得通

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

或者这可能更清楚

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