[英]Renaming columns based on condition about their names
I would like to add a prefix to my dataset column names only if they already begin with a certain string, and I would like to do it (if possible) using a dplyr
pipeline. 我想在我的数据集列名称中添加一个前缀,只要它们已经以某个字符串开头,并且我想使用
dplyr
管道(如果可能)这样做。
Taking the iris
dataset as toy example, I was able to get the expected result with base R (with a quite cumbersome line of code): 以
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
In this example, the prefix YAY_
has been added to all the column names starting with Sepal
. 在此示例中,前缀
YAY_
已添加到以Sepal
开头的所有列名称中。 Is there a way to obtain the same result with a dplyr
command/pipeline? 有没有办法用
dplyr
命令/管道获得相同的结果?
An option would be rename_at
一个选项是
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.