【发布时间】:2021-12-11 10:41:07
【问题描述】:
我有一个数据框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")
相关帖子:
以下帖子是相关的,但它删除了字符串Remove part of column name 的已知部分。就我而言,我想根据在多个数据集中保持相同的部分字符串来检测列的出现。但是一旦在列名中检测到字符串,我想更改整个列名。以下帖子也可能相关但不符合我的需求 r Remove parts of column name after certain characters 或 Rename column names according to pattern matching R
对此的任何建议将不胜感激。谢谢!
【问题讨论】:
标签: r regex string substring rename