2

I have a list of data frames:

 mylist<-list(df1=data.frame(var1=c("a","b","c"), var.2= 
 c("a","b","c")), df2= data.frame(var1 = c("a","b","c"), 
 var..2=c("a","b","c")))

I would like to remove periods and spaces within the column headings of each data frame within the list. The output would look like:

 mylist<-list(df1=data.frame(var1=c("a","b","c"), var2= 
 c("a","b","c")), df2= data.frame(var1= c("a","b","c"), 
 var2=c("a","b","c")))

I have tried the following:

 cleandf <- lapply(ldf, function(x) x[(colnames(x) <- gsub(".", "", 
 colnames(x), fixed = TRUE))])
Danielle
  • 785
  • 7
  • 15

2 Answers2

2

With Base R setNames:

lapply(mylist, function(x) setNames(x, gsub("\\.", "", names(x))))

or with tidyverse:

library(tidyverse)

map(mylist, ~rename_all(.x, str_replace_all, "\\.", ""))

Output:

$df1
  var1 var2
1    a    a
2    b    b
3    c    c

$df2
  var1 var2
1    a    a
2    b    b
3    c    c
acylam
  • 18,231
  • 5
  • 36
  • 45
1

I rename the columns in each data frame and then return the data frame. As explained here, double backslashes are needed as escape characters for the period.

lapply(mylist, function(x){names(x) <- gsub("\\.", "", names(x));x})

# $`df1`
#   var1 var2
# 1    a    a
# 2    b    b
# 3    c    c
# 
# $df2
#   var1 var2
# 1    a    a
# 2    b    b
# 3    c    c
Dan
  • 11,370
  • 4
  • 43
  • 68