简体   繁体   English

如何将函数应用于 tidyverse 中的列名

[英]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.

相关问题 如何在 tidyverse 中将这个 function 与cross() 按列应用? - How to apply this function columnwise with across() in tidyverse? 通过应用函数R传递的同名 - Colnames passed through an apply function R 如何有效地将 cumprod 应用于 tidyverse 中的所有列 - How to efficiently apply cumprod to all columns in the tidyverse 如何使用 tidyverse 应用函数列表并为应用的每个函数取回一列 - How to apply a list of functions using tidyverse and get back a column for each function applied 如何通过“ apply”和“ lapply”操作保留姓氏? - How can I preserve colnames through `apply` and `lapply` operations? 使用 tidyverse 和 mutate_all 对每一列应用相同的函数 - Apply a same function to each column with tidyverse and mutate_all 将具有多个输出的函数应用于按 tidyverse 中的因子拆分的数据帧 - Apply a function with multiple outputs to dataframe that is split by factors in the tidyverse 将具有多列的相同 function 作为输入应用到具有 tidyverse 的 R 中的多列 - Apply the same function with multiple columns as inputs to multiple columns in R with tidyverse 通过使用 tidyverse 更改参数并应用系列函数来调用相同的 function - Call the same function by varying parameters with tidyverse and apply family functions tidyverse 中的 Function - Function in tidyverse
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM