[英]How to apply function to colnames in tidyverse
Just like in title: is there any function that allows applying another function to column names of data frame
?就像标题一样:是否有任何函数可以将另一个函数应用于
data frame
列名? I mean something like forcats::fct_relabel
that applies some function to factor labels.我的意思是像
forcats::fct_relabel
类的东西, forcats::fct_relabel
一些函数应用于因子标签。
To give an example, supose I have a data.frame
as below:举个例子,
data.frame
我有一个data.frame
如下:
X<-data.frame(
firababst = c(1,1,1),
secababond = c(2,2,2),
thiababrd = c(3,3,3)
)
X
firababst secababond thiababrd
1 1 2 3
2 1 2 3
3 1 2 3
Now I wish to get rid of abab
from column names by applying stringr::str_remove
.现在我希望通过应用
stringr::str_remove
从列名中删除abab
。 My workaround involves magrittr::set_colnames
:我的解决方法涉及
magrittr::set_colnames
:
X %>%
set_colnames(colnames(.) %>% str_remove('abab'))
first second third
1 1 2 3
2 1 2 3
3 1 2 3
Can you suggest some more strightforward way?你能提出一些更直接的方法吗? Ideally, something like:
理想情况下,类似于:
X %>%
magic_foo(str_remove, 'abab')
You can do:你可以做:
X %>%
rename_all(~ str_remove(., "abab"))
first second third
1 1 2 3
2 1 2 3
3 1 2 3
使用base R
,我们可以做到
names(X) <- sub("abab", "", names(X))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.