Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to rename column names containing "(N)"?

I’d like to remove the "(N)" from the column names.

Example data:

df <- tibble(
  name = c("A", "B", "C", "D"),
   `id (N)` = c(1, 2, 3, 4),
  `Number (N)` = c(3, 1, 2, 8)
)

I got so far, but don’t know how to figure out the rest of regex

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

df %>% 
  rename_with(stringr::str_replace, 
              pattern = "[//(],N//)]", replacement = "")

But the n from the "number (N)" is gone.

    name    id N)   umber (N)
1   A   1   3
2   B   2   1
3   C   3   2
4   D   4   8

>Solution :

One liner: rename_with(df, ~str_remove_all(., ' \\(N\\)'))

or dplyr only: rename_with(df, ~sub(' \\(N\\)', '', .))

We could use the rename_with function from dplyr package and apply a function (in this case str_remove from stringr package).

And then use \\ to escape (:

library(dplyr)
library(stringr)
df %>% 
  rename_with(~str_remove_all(., ' \\(N\\)'))
  name     id Number
  <chr> <dbl>  <dbl>
1 A         1      3
2 B         2      1
3 C         3      2
4 D         4      8
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading