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))])
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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.