首页 > 解决方案 > 基于现有的索引到 R 中的日期创建新的增长数据表

问题描述

我有以下数据框:df1

行业 2020-01-01 2020-02-01 …… 2021-04-01
矿业 20 10 .. 15
建造 120 40 .. 20

我想创建一个新的数据框,将参考日期设置为 2020-02-01,然后对于剩余的日期,它将计算每行锚定日期的增长率。

所以理想情况下我的新数据框会像这个 df2

行业 2020-02-01 …… 2021-04-01
矿业 0 .. 0.5
建造 0 .. -0.5

谢谢!

标签: r

解决方案


1) dplyr我们可以使用 mutate/across。cross(-1) 是 dat 的第一列。

library(dplyr)
dat %>% mutate(across(-1) / `2020-02-01` - 1)

给予:

      Industry 2020-01-01 2020-02-01 2021-04-01
1       Mining          1          0        0.5
2 construction          2          0       -0.5

2)折叠 使用折叠包我们可以做到这一点。它将指示的函数应用于除第一列之外的所有列。

library(collapse)
tfmv(dat, -1, function(x) x / dat$"2020-02-01" - 1)

给予:

      Industry 2020-01-01 2020-02-01 2021-04-01
1       Mining          1          0        0.5
2 construction          2          0       -0.5

3) data.table 这个包可以如下使用。

library(data.table)

DT <- as.data.table(dat)
timecols <- names(dat)[-1]
DT[, (timecols) := .SD / `2020-02-01` - 1, .SDcols = timecols]

给予:

> DT
       Industry 2020-01-01 2020-02-01 2021-04-01
1:       Mining          1          0        0.5
2: construction          2          0       -0.5

4) Base R 使用 Base R 我们可以这样写:

replace(dat, -1, dat[-1] / dat$"2020-02-01" - 1)

给予:

      Industry 2020-01-01 2020-02-01 2021-04-01
1       Mining          1          0        0.5
2 construction          2          0       -0.5

笔记

dat <- structure(list(Industry = c("Mining", "construction"), `2020-01-01` = c(20L, 
120L), `2020-02-01` = c(10L, 40L), `2021-04-01` = c(15L, 20L)), row.names = c(NA, 
-2L), class = "data.frame")

推荐阅读