R 基于列名称的条件重命名列
仅当数据集列名已经以某个字符串开头时,我才想为它们添加前缀,并且我想(如果可能)使用R 基于列名称的条件重命名列,r,dplyr,rename,R,Dplyr,Rename,仅当数据集列名已经以某个字符串开头时,我才想为它们添加前缀,并且我想(如果可能)使用dplyr管道来添加前缀 以iris数据集为例,我能够使用base R获得预期的结果(代码行相当繁琐): 数据(“iris”) colnames(iris)[startsWith(colnames(iris),“萼片”)]一个选项是rename\u at library(tidyverse) iris %>% rename_at(vars(starts_with("Sepal")), ~ str_c
dplyr
管道来添加前缀
以iris
数据集为例,我能够使用base R获得预期的结果(代码行相当繁琐):
数据(“iris”)
colnames(iris)[startsWith(colnames(iris),“萼片”)]一个选项是rename\u 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
# ...
我不知道,rename
和select
也有它们的作用域变量,我没有想到,我的错。另一个小问题:为什么在stru_c
之前会有一个tilde?@RicS与tidyverse
使用~
的匿名函数约定,否则,你可以使用函数(x)x
一石二鸟,用一个问题学习两个概念总是很好的。谢谢你的帮助!
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
# ...