我有一个数据帧列表:
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")))
我想删除列表中每个数据框的列标题中的句点和空格。输出如下:
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")))
我尝试了以下方法:
cleandf <- lapply(ldf, function(x) x[(colnames(x) <- gsub(".", "",
colnames(x), fixed = TRUE))])
答案 0 :(得分:2)
以基数R V
:
setNames
或使用lapply(mylist, function(x) setNames(x, gsub("\\.", "", names(x))))
:
tidyverse
输出:
library(tidyverse)
map(mylist, ~rename_all(.x, str_replace_all, "\\.", ""))
答案 1 :(得分:1)
我重命名每个数据帧中的列,然后返回数据帧。如here所述,此期间需要使用双反斜杠作为转义字符。
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