Home > OS >  How to rename column names containing "(N)"?
How to rename column names containing "(N)"?

Time:01-05

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

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

CodePudding user response:

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

CodePudding user response:

A possible solution:

library(tidyverse)

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

df %>% names %>% str_remove("\\s*\\(N\\)\\s*") %>% set_names(df,.)

#> # A tibble: 4 × 3
#>   name     id Number
#>   <chr> <dbl>  <dbl>
#> 1 A         1      3
#> 2 B         2      1
#> 3 C         3      2
#> 4 D         4      8

CodePudding user response:

Perhaps you can try

setNames(df, gsub("\\s\\(.*\\)", "", names(df)))

which gives

  name     id Number
  <chr> <dbl>  <dbl>
1 A         1      3
2 B         2      1
3 C         3      2
4 D         4      8

CodePudding user response:

A simple solution is

colnames(df) <- gsub(" \\(N\\)", "", colnames(df))
  •  Tags:  
  • Related