【问题标题】:Changing the column name based on a partial string or substring根据部分字符串或子字符串更改列名
【发布时间】: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 charactersRename column names according to pattern matching R

对此的任何建议将不胜感激。谢谢!

【问题讨论】:

    标签: r regex string substring rename


    【解决方案1】:

    使用来自base RendsWith

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

    根据文档?endsWith,它可能会更快

    startsWith() 等价于但比

    快得多

    substring(x, 1, nchar(prefix)) == 前缀
    或者也

    grepl("^", x)

    【讨论】:

      【解决方案2】:

      另一种解决方案可能是:

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

      【讨论】:

        【解决方案3】:

        将数据框放在一个列表中,并使用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 &lt;- Apple %&gt;% rename_with(~'Growth', matches('Growth Level Judgement'))) 吗?
        • 能否在一个rename_with() 命令中进行多项更改?
        • 你的意思是这样吗? mtcars %&gt;% rename_with(~c('A', 'B'), matches('mpg|cyl')) %&gt;% head
        • 好吧,在不知道您原始数据的详细信息的情况下,我认为我无法进一步调试它。在之前的评论中,我展示了它在mtcars 数据集上的工作原理。如果您无法解决此问题,请随时提出有关原始数据详细信息的新问题。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-13
        • 2021-10-23
        • 2023-04-05
        • 2019-11-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多