Patrik_P
Patrik_P

Reputation: 3200

How to rename a column to today`s date?

I would love to rename a column to today`s date:

I`ve tried the base function Sys.Date() & dplyr pkg in the following syntax:

library(dplyr)
df2 <- df1 %>% select(Column 1, Column 2) %>% rename(toString(Sys.Date())= 'Old Column Name')

Does not work. Any idea?

Upvotes: 1

Views: 1782

Answers (3)

kristang
kristang

Reputation: 557

Using rename_ from dplyr:

df %>% rename_(.dots = setNames("Old Column Name ", sprintf("`%s`", format(Sys.Date(), format = "%Y-%m-%d"))))

Or

# using the built-in 'iris' data:
rename_(iris, .dots = setNames('Species', Sys.Date()))

Upvotes: 7

Spacedman
Spacedman

Reputation: 94277

If you insist on dplyr and pipes, then simply define:

daynamer=function(df, oldname){
     args=list(df, oldname)
     names(args)=c(".data",toString(Sys.Date()))
     do.call(rename_, args)}

Then you can do:

> df1 = data.frame(x=1:5, y=1:5)
> df1 %>% daynamer("x")
  2016-02-18 y
1          1 1
2          2 2
3          3 3
4          4 4
5          5 5

Upvotes: 4

mtoto
mtoto

Reputation: 24198

In base R:

names(df1)[names(df1) == "Old Column Name"] <- as.character(Sys.Date()) 

Upvotes: 10

Related Questions