2

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
writer_typer
  • 708
  • 7
  • 25

4 Answers4

3

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
TarJae
  • 72,363
  • 6
  • 19
  • 66
2

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
PaulS
  • 21,159
  • 2
  • 9
  • 26
2

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
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
1

A simple solution is

colnames(df) <- gsub(" \\(N\\)", "", colnames(df))
rg255
  • 4,119
  • 3
  • 22
  • 40
  • Could this be used in a %>% workflow? – writer_typer Jan 04 '22 at 20:10
  • 1
    @TyperWriter Yes, see [use `%>%` with replacement functions like `colnames()<-`](https://stackoverflow.com/questions/28100780/use-with-replacement-functions-like-colnames/28100903#28100903) – Henrik Jan 04 '22 at 20:41