R add column names which are dates from different months with different lengths

Viewed 100

Is there a good solution to this small problem? I have a csv file that I download and then I change the column names on the file. The first two rows are consistent (Source_1 and Source_2) but the rest of the columns don't have names but they correspond to data from different days of the month. I use colnames to manually add column names but is there a better way to do this? Part of the problem is that different months have different number of days and so the different files will have different lengths. I would like all this to be pretty automated.

april_csv <- read.csv('~/Downloads/april_csv.csv')

length(april_csv) # this value is 31 for the month of April but it might be a different length, depending on the month. 

colnames(april_csv) <- c("Source_1)", "Source_2", "2021-04-01","2021-04-02", "2021-04-03", "2021-04-04", "2021-04-05", "2021-04-06", "2021-04-07", "2021-04-08", "2021-04-09", "2021-04-10", "2021-04-11", "2021-04-12", "2021-04-13", "2021-04-14", "2021-04-15", "2021-04-16", "2021-04-17", "2021-04-18", "2021-04-19", "2021-04-20", "2021-04-21", "2021-04-22", "2021-04-23", "2021-04-24", "2021-04-25", "2021-04-26", "2021-04-27", "2021-04-28", "2021-04-29")

I hope this makes some sense. I wonder if there's a better way.

1 Answers

We can use seq after converting to Date class

library(lubridate)
str1 <- 'april_csv'
date <- mdy(str1, truncated = 2)
year(date) <- year(today())
date_end <- ceiling_date(date,  'month') - 2
nm1 <- as.character(seq(date, date_end, by = '1 day'))
colnames(april_csv) <- c("Source_1", "Source_2", nm1)

Or it can be

nm1 <- as.character(seq(date, length.out = ncol(april_csv)-2, by = '1 day'))
colnames(april_csv) <- c("Source_1", "Source_2", nm1)
Related