Let's Code
Let's Code

Reputation: 99

Adding prefix to column names if a pattern in matched

The data is as follows :

m2 <- data.frame(a = c(1:5),b = c(1:5),"2016"= c(1:5),"2017"= c(1:5),"2018"= c(1:5),"2019" = c(1:5))

I want to add "ABC" before all column name that are years.

2016 should be ABC_2016 2017 should be ABC_2017 ... 2032 should be ABC_2032

Upvotes: 1

Views: 45

Answers (1)

David
David

Reputation: 10162

How about this one?

The code takes the names of a data.frame, checks if the name contains four digits using regex (\\d{4}). If it finds it, it prefixes it with ABC_, otherwise only the old variable name is used.

Note however, that the year variable names are prefixed with an X by data.frame() as it does not accept only numbers per se...

m2 <- data.frame(
  a = c(1:5),
  b = c(1:5),
  "2016"= c(1:5),
  "2017"= c(1:5),
  "2018"= c(1:5),
  "2019" = c(1:5)
)

m2
#>   a b X2016 X2017 X2018 X2019
#> 1 1 1     1     1     1     1
#> 2 2 2     2     2     2     2
#> 3 3 3     3     3     3     3
#> 4 4 4     4     4     4     4
#> 5 5 5     5     5     5     5

n <- names(m2)

is_year <- grepl("\\d{4}", n)
n <- ifelse(is_year, paste0("ABC_", n), n)
names(m2) <- n
m2
#>   a b ABC_X2016 ABC_X2017 ABC_X2018 ABC_X2019
#> 1 1 1         1         1         1         1
#> 2 2 2         2         2         2         2
#> 3 3 3         3         3         3         3
#> 4 4 4         4         4         4         4
#> 5 5 5         5         5         5         5

Created on 2020-06-15 by the reprex package (v0.3.0)

Upvotes: 1

Related Questions