簡體   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