簡體   English   中英

如何重命名包含“(N)”的列名?

[英]How to rename column names containing "(N)"?

我想從列名中刪除“(N)”。

示例數據:

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

我到目前為止,但不知道如何找出正則表達式的 rest

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

但是“數字(N)”中的 n 消失了。

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

一個班輪: rename_with(df, ~str_remove_all(., ' \\(N\\)'))

或僅dplyrrename_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).

然后使用\\轉義( :

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

一個可能的解決方案:

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

也許你可以試試

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

這使

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

一個簡單的解決方案是

colnames(df) <- gsub(" \\(N\\)", "", colnames(df))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM