带有以下数据:
#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)
)
我最终希望拟合一个模型,该模型试图将波动与物理上传统的阻尼振荡器函数进行比较。这是我的问题的图形视图:
可能是我对如何使时间连续感到很愚蠢,但重要的是要保留这些值,而不仅仅是一个单变量的时间序列数据帧。否则,这就是我要做的。但是还有一个因素变量也应保留。
It should look more like this (excel quick graph) but I need to extract the mathematical guts of the function for such lines that would trace the peaks of the curve in the R output:
A solution would involve both: 1) being able to reproduce the curve in R, and 2) generating the density data over time needed to start fitting polynomial models.
Here's the Density plot for the fake data:
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())
Now, if you wanted to make that into a line plot, you could calculate the highest density value for each treatment-time pair and then plot it:
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")
The last part of your ask was to generate the density data over time. If I understand what you want to do, you could do it as follows:
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
The x
variable is the evaluation point for intensity and the y
variable is the height of the density curve for that value of x
.
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句