Logan Logan - 1 month ago 10
R Question

Renaming columns with gsub fails

Tried renaming columns using:

rename_(.dots=setNames(names(.), gsub("`<?(-?[0-9A-Z]*)>?`", "Port\\1", names(.))))


But got the following error:

Error in parse(text = x) : <text>:1:1: unexpected '<'


Below is a full test case:

library(dplyr)
library(readr)

l <- list(`1` = 1:500, `2` = 1:500, `<NA>` = 1:500)
df <- as_data_frame(l)

df %>% rename_(.dots = setNames(names(.), gsub("`<?(-?[0-9A-Z]*)>?`", "Port\\1", names(.))))


Below are some examples as what the regex should do:

> gsub("`<?(-?[0-9A-Z]*)>?`", "Port\\1", "`2`")
[1] "Port2"
> gsub("`<?(-?[0-9A-Z]*)>?`", "Port\\1", "`1`")
[1] "Port1"
> gsub("`<?(-?[0-9A-Z]*)>?`", "Port\\1", "`<NA>`")
[1] "PortNA"
> gsub("`<?(-?[0-9A-Z]*)>?`", "Port\\1", "`-2`")
[1] "Port-2"

Answer

The backticks need to be around the name you're referencing, not the pattern:

df %>% rename_(.dots = setNames(paste0('`', names(.), '`'), 
                                gsub("<?(-?[0-9A-Z]*)>?", "Port\\1", names(.))))

## # A tibble: 500 × 3
##    Port1 Port2 PortNA
##    <int> <int>  <int>
## 1      1     1      1
## 2      2     2      2
## 3      3     3      3
## 4      4     4      4
## 5      5     5      5
## 6      6     6      6
## 7      7     7      7
## 8      8     8      8
## 9      9     9      9
## 10    10    10     10
## # ... with 490 more rows