使用 r 中的 start with 重命名多个列

标签 r dplyr rename

我想重命名以相同字符串开头的多个列。 但是,我尝试的所有代码都没有更改列。

例如:

df %>% rename_at(vars(matches('^oldname,\\d+$')), ~ str_replace(., 'oldname', 'newname'))

还有这个:

df %>% rename_at(vars(starts_with(oldname)), funs(sub(oldname, newname, .))

您熟悉合适的重命名代码吗?

谢谢!

最佳答案

iris为例,您可以使用rename_with()将那些以"Petal"开头的列名替换为新字符串。

head(iris) %>%
  rename_with(~ sub("^Petal", "New", .x), starts_with("Petal"))

  Sepal.Length Sepal.Width New.Length New.Width Species
1          5.1         3.5        1.4       0.2  setosa
2          4.9         3.0        1.4       0.2  setosa
3          4.7         3.2        1.3       0.2  setosa
4          4.6         3.1        1.5       0.2  setosa
5          5.0         3.6        1.4       0.2  setosa
6          5.4         3.9        1.7       0.4  setosa

在这种情况下,您还可以使用 rename_at(),尽管 rename_if()rename_at()rename_all( ) 已被 rename_with() 取代。

head(iris) %>%
  rename_at(vars(starts_with("Petal")), ~ sub("^Petal", "New", .x))

关于使用 r 中的 start with 重命名多个列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72144323/

相关文章:

python - 在 Pandas 中重命名 "None"值

r - 将变量传递给 ggplot2 的 aes() 中的 cut()

r - 使用 R 向 ggplot2 中的绘图添加带箭头的单箭头

r - 创建决策树

r - 按组将 data.frame 拆分为向量列表而不是 data.frames 列表

r - 计算 data.table 中每个组的行本身之前的唯一值

r - 在 dbplyr 中传递要作为函数参数应用的函数

R 使用管道运算符时的条件评估 %>%

Pandas 用通配符重命名列

Python,如何根据列表重命名多个文件?