nuke
nuke

Reputation: 45

How to convert multiple selected column names from integer to date in r

I have a data set with column names that look like this.

INPUT

Country  X1.22.20 X1.23.20 X1.24.20 X1.25.20 X1.26.20 X1.27.20 
    India      40        20      30       21       25      28
    USA        21        22      23       45       32      19
    CHINA      30        45      32       46       78      48

X1.22.20 represents 1/22/2020

Required Output

Country  01/22/20 01/23/20 01/24/20 01/25/20 01/26/20 01/27/20 
     India      40        20      30       21       25      28
     USA        21        22      23       45       32      19
     CHINA      30        45      32       46       78      48

Upvotes: 0

Views: 153

Answers (1)

akrun
akrun

Reputation: 887651

We can avoid this conversion, if we read with check.names = FALSE

df1 <- read.csv('file.csv', check.names = FALSE, stringsAsFactors = FALSE)

if we already read it without the check.names = FALSE option, convert to Date class and then format

names(df1)[-1] <- format(as.Date(names(df1)[-1], format = "X%m.%d.%y"), "%m/%d/%y")

Or another option is sub

names(df1)[-1] <- sub("^X(\\d+)\\.(\\d+)\\.(\\d+)", "\\1/\\2/\\3", names(df1)[-1])

Upvotes: 1

Related Questions