T-T T-T - 3 months ago 9
R Question

How to remove ".x" from column names in the dataframe?

I'm working on a large data set. While using

as.yearmon
to combine values from the same month, I have to use
make.unique(names(df))
to create unique names for each column. From
names(df)
, I can see that
".x",".y",".1",".2"
etc. were added to some of the column names.

I can use
gsub(".x","",names(df),fixed = TRUE)
to remove
".x",".y"
, but the problem is that my column names are numeric like:

name 1.0 1.1 1.2


With
".1",".2"
, the column names become:

name 1.0.1 1.1.1 1.2.2


If I use
gsub(".1","",names(df),fixed = TRUE)
and
gsub(".2","",names(df),fixed = TRUE)
, the colume names will then become:

name 1.0 1 1


My question is that if there is a way to removed the added
".1", ".2"
from the column names without changing the original names?

Answer

How about making sure you're only removing tags at the end of a label?

ndf <- c("1.0.1","1.1.1","1.2.2")
gsub("\\.[0-2]$","",‌​ndf)