如何将我的时间 "bins" 转换为连续时间以在 R 中进行时间序列分析?

How do I convert my time "bins" to continous for a time series analysis in R?

具有以下数据:

#demo data:
set.seed(1234)

library(tidyverse)
library(fs)
n = 100
time= c(15, 30, 60, 90, 120, 180, 240, 300)
treat = factor(c("trt1", "trt2", "tr1+2", "trt1+2+3"))
intensity = c(sample(1:400, n, replace=TRUE))
              df <- expand.grid(time= time, treat = treat, intensity=intensity)
df <- data.frame(
                time= rep(df$time, each = 100),
                intensity = rep(df$intensity),
                treat = rep(df$treat, each = 100)
)

我最终希望拟合一个模型,该模型试图将波动与物理学中的传统阻尼振荡器函数进行比较。这是我的问题的图形:

这可能是我对如何使时间连续在这里很愚蠢,但重要的是要保留这些值并且它不仅仅是一个单变量时间序列数据框。否则,这就是我会做的。但是还有一个治疗因素变量也应该保留。

它应该看起来更像这样(excel 快速图表)但我需要提取函数的数学内脏,以跟踪这些线的峰值R输出中的曲线:

解决方案将涉及:1) 能够在 R 中重现曲线,以及 2) 随时间生成开始拟合多项式模型所需的密度数据。

这是假数据的密度图:

df %>% 
  ggplot(aes(x=intensity, fill=treat)) + 
  geom_density(color="transparent", alpha=.25) + 
  facet_wrap(~as.factor(time), nrow=1) + 
  theme_bw() + 
  theme(panel.grid=element_blank())

现在,如果您想将其制作成线图,您可以计算每个治疗时间对的最高密度值,然后绘制它:

df %>% group_by(treat, time) %>% 
  summarise(d = max(density(intensity)$y)) %>% 
  ggplot(aes(x=time, y=d, colour=treat)) + 
  geom_point() + 
  geom_line() + 
  theme_classic() + 
  labs(x="Time", y="Intensity")

您要求的最后一部分是随时间生成密度数据。如果我明白你想做什么,你可以这样做:

out <- df %>% group_by(treat, time) %>% 
  summarise(as.data.frame(density(df$intensity)[c("x", "y")]))

head(out)
# # A tibble: 6 x 4
# # Groups:   treat, time [1]
#   treat  time     x          y
#   <fct> <dbl> <dbl>      <dbl>
# 1 tr1+2    15 -20.5 0.00000608
# 2 tr1+2    15 -19.6 0.00000838
# 3 tr1+2    15 -18.7 0.0000114 
# 4 tr1+2    15 -17.8 0.0000153 
# 5 tr1+2    15 -17.0 0.0000203 
# 6 tr1+2    15 -16.1 0.0000267 

x变量是强度的评估点,y变量是x.

值的密度曲线高度