【发布时间】:2019-06-13 11:51:31
【问题描述】:
我想计算几年来每一天的趋势。例如从 2000 年到 2010 年 5 月 1 日的趋势。这是我的测试数据框:
library(lubridate)
date_list = seq(ymd('2000-01-15'),ymd('2010-09-18'),by='day')
testframe = data.frame(Date = date_list)
testframe$Day = substr(testframe$Date, start = 6, stop = 10)
testframe$V1 = rnorm(3900)
testframe$V2 = rnorm(3900)
testframe$V3 = seq(from = 10, to = 25, length.out = 3900)
testframe$V4 = seq(from = 5, to = 45, length.out = 3900)
V1 到 V4 是值。在 testframe$Day 中,我已经删除了这一天,以便我可以使用它来对行进行分组。我知道aggregate 适合以这种方式进行分组,但我很不知道如何将它与线性模型结合起来。
最后,我希望有一个数据框,其中有一列包含每一天(当然不包括年份)和包含从 V1 到 V4 值的趋势/斜率的列。
有什么想法吗?
更新:
为了更清楚。我想要和输出看起来像这样(趋势是随机的)
Day V1 Trend V2 Trend V3 Trend V4 Trend
01-01 +0.3 +0.4 +0.9 +0.5
01-02 +0.5 +0.3 +0.8 +0.4
01-03 -0.1 -0.2 +1.0 -0.3
01-04 +0.7 -0.7 +0.9 +0.9
......
......
12-30 -0.3 -0.4 +0.5 +0.8
12-31 -0.7 -0.3 +0.6 +0.9
p-values、Intercept 和所有这些都很棒。
我找到了这个例子,但它仍然不在我想要的输出中:
#Add year for lm
testframe$Year = as.numeric(format(testframe$Date,'%Y'))
library(plyr)
# Break up d by state, then fit the specified model to each piece and
# return a list
models <- dlply(testframe, "Day", function(df)
lm(Year ~ V4, data = df))
# Apply coef to each model and return a data frame
ldply(models, coef)
# Print the summary of each model
l_ply(models, summary, .print = TRUE)
【问题讨论】:
标签: r date linear-regression lm trend