2

In this dummy list of data frames, all column names have a prefix followed by an underscore. Each data frame in the list has a different prefix, but they all include an underscore.

How can I remove the underscore and the text before it in the column names of all data frames in the list? I can do it individually, but my real list contains many more data frames. Thank you

#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))
J.Con
  • 4,101
  • 4
  • 36
  • 64
  • You just need to do this for each element of the list. https://stackoverflow.com/questions/12297859/remove-all-text-before-colon – Ronak Shah Jul 18 '18 at 01:46

1 Answers1

2

We can use lapply to loop through the list, remove the prefix of the column names with sub, and set the names with setNames

lapply(mylist, function(x) setNames(x, sub("^[^_]*_", "", names(x))))

Or using tidyverse, loop through the list with map and remove the substring of the column names with str_remove inside rename_all

library(tidyverse)
map(mylist, ~  .x %>% 
                  rename_all(~ str_remove(.x, "^[^_]*_")))
akrun
  • 874,273
  • 37
  • 540
  • 662