user13267770
user13267770

Reputation:

add pattern to colnames that match another pattern

i want to add "good" to the columns which are named "bye".

df <- tibble("hi" = c(1,2,3), "bye1" = c(1,2,3), "bye2" = c(1,2,3))
df
# A tibble: 3 x 3
     hi  bye1  bye2
  <dbl> <dbl> <dbl>
1     1     1     1
2     2     2     2
3     3     3     3

Here i could just use:

colnames(df)[2:3] <- c("goodbye1", "goodbye2")

But my real is df has several hundred columns and that would be too much to type. So i want to look for the pattern "bye" and add an "good" to all of those. I tried this:

colnames(df[ , grepl("bye", names(df))])
[1] "bye1" "bye2"

paste0("good", colnames_bye)
[1] "goodbye1" "goodbye2"

but combining that like

colnames(df[ , grepl("bye", names(df))]) <- paste0("good", colnames_bye)

Gives nothing. No warning, no error, no change. R just ignores the command. What am i doing wrong?

Upvotes: 0

Views: 60

Answers (1)

maydin
maydin

Reputation: 3755

The problem with your code is that in this case

colnames(df[ , grepl("bye", names(df))])

is a new object that is created, updated, and unasigned.

rather than creating a new object, you should just update a subset of colnames(df). See the difference when you use the ( )[ ] code instead of ( [ ] ).

colnames(df)[grepl("bye", names(df))] <- paste0("good", colnames(df)[grepl("bye", names(df))] )

gives,

     hi goodbye1 goodbye2
  <dbl>    <dbl>    <dbl>
1     1        1        1
2     2        2        2
3     3        3        3

Upvotes: 0

Related Questions