繁体   English   中英

根据有关其名称的条件重命名列

[英]Renaming columns based on condition about their names

我想在我的数据集列名称中添加一个前缀,只要它们已经以某个字符串开头,并且我想使用dplyr管道(如果可能)这样做。

iris数据集作为玩具示例,我能够用基数R获得预期结果(使用相当繁琐的代码行):

data("iris")
colnames(iris)[startsWith(colnames(iris), "Sepal")] <- paste0("YAY_", colnames(iris)[startsWith(colnames(iris), "Sepal")])
head(iris)
  YAY_Sepal.Length YAY_Sepal.Width Petal.Length Petal.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

在此示例中,前缀YAY_已添加到以Sepal开头的所有列名称中。 有没有办法用dplyr命令/管道获得相同的结果?

一个选项是rename_at

library(tidyverse)
iris %>% 
   rename_at(vars(starts_with("Sepal")), ~ str_c("YAY_", .)) 
#   YAY_Sepal.Length YAY_Sepal.Width Petal.Length Petal.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
# ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM