首页 > 解决方案 > R - 从 [ 符号后的列名中删除文本

问题描述

我在 R 中有一个名为 hues 的数据框

它有 3 列,分别称为 color1 [primary]、color2 [secondary]、color3 [tertiary]

我尝试过使用 sub / gsub 等,但没有找到解决方案

有谁能帮忙吗?

names(hues) = gsub(pattern = "\\[*", replacement = "", x = names(hues))

我有这个

color1 [primary]     color2 [secondary]    color3 [tertiary]
blue                pink                  red

我要这个

color1              color2                color3 
blue                pink                  red

标签: r

解决方案


您需要在.before中添加*,以表明您要在之后替换任意数量的字符[。还要在之前添加一个空格\\[以删除该空格。我将列名转换为字符向量,但替换exnames(hues)您的hues数据框,并且显然将其分配回来,因为它只是在此处打印输出。

ex <- c("color1 [primary]", "color2 [secondary]", "color3 [tertiary]")
gsub(" \\[.*", "", ex)
#> [1] "color1" "color2" "color3"

reprex 包(v0.2.1)于 2019 年 2 月 6 日创建


推荐阅读