[英]remove suffix from column names using rename_at in r
我有一個 dataframe,其中許多列以相同的后綴結尾,我想使用 rename_at() 將它們全部刪除,但我無法弄清楚。
library(tidyverse)
my_df <- tibble(id = c(1, 2),
jan_real = c(8, 10),
feb_real = c(9, 10),
mar_real = c(1, 11))
desired_df <- tibble(id = c(1, 2),
jan = c(8, 10),
feb = c(9, 10),
mar = c(1, 11))
您現在應該使用從dplyr 1.0.0
取代rename_at()
rename_with()
rename_with() :
library(dplyr)
my_df %>%
rename_with(~ sub("_real$", "", .x), everything())
# A tibble: 2 x 4
id jan feb mar
<dbl> <dbl> <dbl> <dbl>
1 1 8 9 1
2 2 10 10 11
使用rename_at()
:
my_df %>%
rename_at(vars(everything()), ~ sub("_real$", "", .x))
你可以試試這個方法
library(dplyr)
library(stringr)
my_df %>%
rename_at(vars(matches("_real")), ~str_remove(., "_real"))
# id jan feb mar
# <dbl> <dbl> <dbl> <dbl>
# 1 1 8 9 1
# 2 2 10 10 11
您可以在setNames
中嘗試gsub
desired_df <- setNames(my_df,gsub("_.*","",names(my_df)))
這樣
> desired_df
# A tibble: 2 x 4
id jan feb mar
<dbl> <dbl> <dbl> <dbl>
1 1 8 9 1
2 2 10 10 11
在base R
中,如果我們將whitespace
指定為正則表達式以匹配_
后跟字符 ( .*
),我們也可以使用trimws
names(my_df) <- trimws(names(my_df), whitespace = "_.*")
my_df
# A tibble: 2 x 4
# id jan feb mar
# <dbl> <dbl> <dbl> <dbl>
#1 1 8 9 1
#2 2 10 10 11
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.