如何将时间序列中的列除以它们在 R 中的第一个值?

问题描述 投票:0回答:2

我有下面的代码。但必须有更好的方法。

file <- "http://s3.amazonaws.com/assets.datacamp.com/production/course_1127/datasets/tmp_file.csv"
x <- read.csv(file = file)
ts <- xts(x = x,  order.by = as.Date(rownames(x), "%m/%d/%Y"))
cd=coredata(ts)
for (j in 1:length(names(ts)))  cd[,j]<-cd[,j]/cd[1,j]
for (j in 1:length(names(ts))) ts[,j]<-cd[,j]
r matrix time-series xts
2个回答
1
投票

我们可以使用

apply
将每一列除以它的第一个值:

file <- "http://s3.amazonaws.com/assets.datacamp.com/production/course_1127/datasets/tmp_file.csv"
x <- read.csv(file = file)

library(xts)
ts <- xts(x = x, order.by = as.Date(rownames(x), "%m/%d/%Y"))

ts <- apply(ts, 2, function(x) x / x[1])

           a        b
2015-01-02 1 1.000000
2015-02-03 2 1.333333

0
投票

您可以通过重复该行从所需的缩放行创建一个矩阵,然后将原始数据除以该缩放矩阵:

> ts <- xts(x = x,  order.by = as.Date(rownames(x), "%m/%d/%Y"))
> ts
           a b
2015-01-02 1 3
2015-02-03 2 4
> m <- matrix(rep(coredata(ts)[1,], nrow(ts)), ncol = 2, byrow = TRUE)
> m
     [,1] [,2]
[1,]    1    3
[2,]    1    3
> coredata(ts) <- coredata(ts) / m
> ts
           a       b
2015-01-02 1 1.00000
2015-02-03 2 1.33333
> 

即简洁,但牺牲内存。 @TarJae 的回答很好,但内存效率可能很高,所以我已经投票了。

© www.soinside.com 2019 - 2024. All rights reserved.