r语言 - 基于部分字符串或子字符串更改列名



我有一个数据帧df。我可以为5个不同的变量生成5次这个数据帧。比如变量名是:

Apple  # apple_df
Mango  # mango_df
Banana # banana_df
Potato # potato_df
Tomato # tomato_df

每次生成数据帧时,其中一个列名相当大,例如:

Apple - Growth Level Judgement    # Column name for apple_df
Mango - Growth Level Judgement    # Column name for mango_df
Banana - Growth Level Judgement   # Column name for banana_df
Potato - Growth Level Judgement   # Column name for potato_df
Tomato - Growth Level Judgement   # Column name for tomato_df

我想在每个文件中将上面的列名更改为只使用单词Growth

是否有一种方法可以通过使用一行代码(单独)有效地跨所有数据帧?

我可以在每个文件中单独使用完整的名称,但我想知道我们是否可以有一个通用的解决方案:

# For Apple data frame
# Update column name
setnames(apple_df, 
old = c('Apple - Growth Level Judgement'), 
new = c('Growth'))

如果我使用以下基于正则表达式的解决方案,它只替换所有数据帧中常见的字符串名称部分。不幸的是,不是全名。

gsub(x = names(apple_df), 
pattern = "Growth Level Judgement$", replacement = "Growth")  

相关文章:

下面的帖子是相关的,但它剥离了字符串的已知部分,删除了列名的部分。在我的例子中,我想检测基于在多个数据集中保持相同的部分字符串的列的出现情况。但是,一旦在列名中检测到字符串,我就想更改整个列名。下面的帖子也可能是相关的,但不符合我的需要r删除列名中某些字符之后的部分或根据模式匹配重命名列名r

如有任何建议,我将不胜感激。谢谢!

endsWith代替base R

names(Apple)[endsWith(names(Apple), 'Growth Level Judgement')] <- 'Growth'

基于?endsWith文档,它可以更快

startsWith()相当于

,但比 快得多

substring(x, 1, nchar(prefix)) == prefix

grepl("^",x)

将数据框放在列表中,并使用lapply/map更改每个数据框的名称。list2env将这些更改从列表转移到单个数据框架。

library(dplyr)
library(purrr)
list_df <- lst(Apple, Mango, Banana, Potato, Tomato)
list_df <- map(list_df, 
~.x %>% rename_with(~'Growth', matches('Growth Level Judgement')))
list2env(list_df, .GlobalEnv)

要在单个数据帧上运行,可以执行-

Apple %>% rename_with(~'Growth', matches('Growth Level Judgement')))

或以R为底-

names(Apple)[grep('Growth Level Judgement', names(Apple))] <- 'Growth'

另一种解决方案是:

Apple %>% 
rename_with(~'Growth', ends_with('Growth Level Judgement'))

最新更新