Srl844
Srl844

Reputation: 1

Replacing pattern in Column names of R-Tibble

I am trying to update 23 column names in a tibble in an RMD document that all follow the same pattern (1999-05, 2000-05, etc). I am trying to remove the "-05" so it just says the year. When I have attempted to use gsub("-05"), ""), it tells me I'm missing an argument. When I add anything as the third argument, it turns my tibble into a set of values instead.

I have also attempted <- str_remove_all('-05', '') and it returns that the pattern is not supported.

Any suggestions??

Upvotes: 0

Views: 374

Answers (1)

Simon Mills
Simon Mills

Reputation: 188

It sounds like you are using dplyr already: with dplyr you can use rename_all to remove the same string from all columns, or rename_at to rename a subset of columns (in below code it is any columns containing 2000).

library(dplyr)

df <- tibble(`1999-05` = NA, `2000-05` = NA, `2001-05` = NA)

df %>%
    rename_all(function(x) gsub("-05$", "", x))

df %>%
    rename_at(vars(contains("2000")), function(x) gsub("-05$", "", x))

Upvotes: 1

Related Questions