我有一个看起来像的数据框
a <- c(118200,251482,325641)
b <- c(251463,524198,623144)
c <- c(251796,201534,62498)
df <- as.data.frame(cbind(a,b,c), row.names = c('2013','2014','2015'))
> df
a b c
2013 118200 251463 251796
2014 251482 524198 201534
2015 325641 623144 62498
我希望通过将每个观察值除以365而不是年份来获取每日信息,并且每年的最后一天总计为年度总数。即
a b c
2013-01-01 326.83 688.94 689.85
2013-01-02 647.67 1377.88 1379.70
2013-01-03 971.50 2066.82 2069.56
. . . .
. . . .
2013-12-31 118200 251463 251796
与2014和2015年相同。我该怎么做?
答案 0 :(得分:2)
可以做到:
library(data.table)
setDT(df, keep.rownames = TRUE)
cols <- setdiff(names(df), "rn")
df <- df[, .(Day = seq(as.Date(paste0(rn, "-01-01")),
as.Date(paste0(rn, "-12-31")),
by = "day")),
by = names(df)][
, (cols) := lapply(.SD, function(x) round( (x / .N) * (1:.N), 2)),
.SDcols = cols,
by = rn][, "rn" := NULL]
2013
开头和2015
结尾的输出:
a b c Day
1: 323.84 688.94 689.85 2013-01-01
2: 647.67 1377.88 1379.70 2013-01-02
3: 971.51 2066.82 2069.56 2013-01-03
4: 1295.34 2755.76 2759.41 2013-01-04
5: 1619.18 3444.70 3449.26 2013-01-05
---
1091: 322072.33 616315.02 61813.09 2015-12-27
1092: 322964.50 618022.27 61984.32 2015-12-28
1093: 323856.67 619729.51 62155.55 2015-12-29
1094: 324748.83 621436.76 62326.77 2015-12-30
1095: 325641.00 623144.00 62498.00 2015-12-31