简体   繁体   English

R 添加列名称,这些名称来自不同月份的不同长度的日期

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

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.我下载了一个 csv 文件,然后更改了文件上的列名。 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.前两行是一致的(Source_1 和 Source_2),但列的 rest 没有名称,但它们对应于一个月中不同日期的数据。 I use colnames to manually add column names but is there a better way to do this?我使用 colnames 手动添加列名,但有更好的方法吗? 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.我想知道是否有更好的方法。

We can use seq after converting to Date class我们可以在转换为Date class 后使用seq

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM