r - 基于现有的索引到 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 |
谢谢!
解决方案
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")
推荐阅读
- mips - lw add 和 sw 的行如何转换为下图?
- c# - 带有表达式树的数据集分组依据
- r - 在数据框列中显示唯一字符
- android - 在 android 公共类 ImageDownlod 扩展 AsyncTask
在类 ImageDownlod 在第二个变量中使用 void 时给我错误...
使用 void 错误
此处错误无效
public class ImageDownlod extends AsyncTask<
- python-3.x - Python coinflip 代码问题:如何删除 .text 文件中的行?
- java - 向 SOAP 请求添加摘要身份验证
- json - Angular 将多个 JSON 文件合并为一个
- javascript - 失败:无效参数 -Protractor
- javascript - 使用 d3-tip.js 在悬停时显示工具提示
- ruby-on-rails - 如何将 devise_for 控制器重定向到默认设计以外的其他控制器