【发布时间】:2021-11-04 04:37:21
【问题描述】:
问题:
我想通过替换某些重复的字符串来重命名大量列名。
Reprex:
library(dplyr)
library(stringr)
code <- c(round(runif(26, 0, 100),0))
names <- letters
AIYN <- stringi::stri_rand_strings(26, 2)
SIYN <- stringi::stri_rand_strings(26, 2)
df <- bind_cols(code, names, AIYN, SIYN)
colnames(df) <- c("code (2021)", "names (2021)", "all the info you need (AIYN) from A to Z",
"some info you need (SIYN) from A to Z")
View(df)
尝试的解决方案
colnames(df) <- str_replace_all(colnames(df), "[(2021)]", "")
colnames(df) <- str_replace_all(colnames(df), "all the info you need (AIYN) from A to Z", "AIYN")
colnames(df) <- str_replace_all(colnames(df), "some info you need (SIYN) from A to Z", "SIYN")
目标
我想删除带有数字的括号(例如“(2019)”),并保留括号中的字符,其中只有字符(例如“(AIYN)”,“(SIYN)”)。我的解决方案冗长,因为我的数据框有一百多列。
【问题讨论】:
-
我想知道
colnames(df) <- coalesce(str_extract(colnames(df), '(?<=\\()[A-Za-z]+(?=\\))'), str_replace_all(colnames(df), "\\s*\\(\\d+\\)", ""))是否适合您。