在这个数据框的虚拟列表中,所有列名称都有一个前缀,后跟一个下划线。列表中的每个数据框都有不同的前缀,但它们都包含下划线。
如何删除列表中所有数据框的列名称中的下划线及其前面的文本?我可以单独完成,但我的真实列表包含更多数据框。谢谢
#add diferent prefixes to all col names
colnames(iris)<-paste('iris_',colnames(iris), sep='')
colnames(mtcars)<-paste('mt_',colnames(mtcars), sep='')
colnames(ToothGrowth)<-paste('TG_',colnames(ToothGrowth), sep='')
#create list of data frames
mylist<-list(iris, mtcars, ToothGrowth)
#name elements of list
names(mylist)<-c('iris','mtcars','ToothGrowth')
#remove prefix from colnames individually for each data frame
colnames(mylist['iris']$iris)<-sub('[^.]+\\_', '', colnames(mylist['iris']$iris))
最佳答案
我们可以使用lapply
循环遍历 list
,删除列名的前缀 sub
,并将名称设置为 setNames
lapply(mylist, function(x) setNames(x, sub("^[^_]*_", "", names(x))))
或者使用tidyverse
,循环遍历list
与 map
并使用 str_remove
删除列名称的子字符串里面rename_all
library(tidyverse)
map(mylist, ~ .x %>%
rename_all(~ str_remove(.x, "^[^_]*_")))
关于删除数据框列表中的部分列名称 - R,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51392362/