英文:
How to divide the columns in a time series by their first value in R?
问题
以下是代码的中文翻译部分:
我已经让下面的代码工作了。但一定有更好的方法。
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]
英文:
I have the code below working. But there must be a better way.
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]
答案1
得分: 2
你可以通过重复所需的缩放行来创建一个矩阵,然后将原始数据除以该缩放矩阵:
> 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 的回答可能更节省内存,我已经点赞了。
英文:
You can create a matrix from your desired scaling row by repeating the row, and then divide the original data by that scaling matrix:
> 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
>
That is concise, but the expense of memory. The answer by @TarJae is as nice but possiblt memory efficient so I already upvoted it.
答案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
英文:
We can use apply
to divide each column by its first value:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论