Question

Consider the following:

df <- list(df1 = data.frame(a.1 = 1, b..2 = 2), df2 = data.frame(c.1 = 3, d...4 = 5, e..3 = 8))
## $df1
##   a.1 b..2
## 1   1    2

## $df2
##   c.1 d...4 e..3
## 1   3     5    8

names(df[[1]])
## [1] "a.1"  "b..2"

Now, for example, I would like to remove the dotes out of the data frames' names so the output will be

## $df1
##   a1 b2
## 1   1    2

## $df2
##   c1 d4 e3
## 1   3     5    8

Obvioulsy the following won't work

lapply(names(df), function(x) gsub("[.]", "", x))

Neither will this

lapply(df[attributes(df)$names], function(x) gsub("[.]", "", x))

a for loop works though

for(i in 1:length(df)){names(df[[i]]) <- gsub("[.]", "", names(df[[i]]))}
## $df1
##   a1 b2
## 1  1  2

## $df2
##   c1 d4 e3
## 1  3  5  8

Edit

@jdharrison solution is very nice, but i was looking to find a way to operate only on the attributes rather on the whole data set (like in the for loop), something like

df2 <- list(a..1 = 2, b..3 = 5)
names(df2) <- lapply(names(df2), function(x) gsub("[.]", "", x))
Was it helpful?

Solution

Something like this maybe?

lapply(df, function(x){ 
  `names<-`(x, gsub("[.]", "",names(x)))
}
)

> lapply(df, function(x){ `names<-`(x, gsub("[.]", "",names(x)))})
$df1
  a1 b2
1  1  2

$df2
  c1 d4 e3
1  3  5  8
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top