![](/img/trans.png)
[英]How to add a column in a dataframe using information from another dataframe with different lengths in R?
[英]R add column names which are dates from different months with different lengths
这个小问题有好的解决办法吗? 我下载了一个 csv 文件,然后更改了文件上的列名。 前两行是一致的(Source_1 和 Source_2),但列的 rest 没有名称,但它们对应于一个月中不同日期的数据。 我使用 colnames 手动添加列名,但有更好的方法吗? 部分问题是不同的月份有不同的天数,因此不同的文件会有不同的长度。 我希望这一切都非常自动化。
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")
我希望这有点道理。 我想知道是否有更好的方法。
我们可以在转换为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)
或者它可以是
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.