Varun
Varun

Reputation: 1321

R convert column names that contain dates to 'Month Year' format

My dataset looks like this -

dataset = data.frame(ID=c(1:5),"2019-03-31"=runif(5,0,1),"2019-04-30"=runif(5,0,1),"2019-05-31"=runif(5,0,1),Avg=runif(5,0,1),Var=runif(5,0,1))

#Correct date names
names(dataset)[2]="2019-03-31"
names(dataset)[3]="2019-04-30"
names(dataset)[4]="2019-05-31"

I'm trying figure out how to convert the dates in the column names to Month Year format.

That is, the column name "2019-03-31" would become March 2019

My attempt is resulting in an empty column name

names(dataset)[2]=as.Date(names(dataset)[2],format="%B %Y")

Any guidance in the right direction would be highly appreciated.

Upvotes: 1

Views: 559

Answers (1)

neilfws
neilfws

Reputation: 33802

Try:

colnames(dataset)[2:4] <- format(as.Date(colnames(dataset)[2:4]), "%b %Y")

Also when creating the example dataset, use check.names = FALSE to avoid adding X to the start of the dates.

Upvotes: 1

Related Questions