连续时间数据的分位数

时间:2013-12-30 19:58:30

标签: r plot continuous quantile

我有100名受试者的血液浓度与时间数据。我有兴趣绘制5,50和95%分位数浓度与时间曲线。虽然我可以确定整个浓度范围的分位数,但我无法在R中弄清楚如何按时间对浓度分位数进行分层。任何帮助将不胜感激。

a<-quantile(conc~time, 0.05) 

不起作用。

3 个答案:

答案 0 :(得分:2)

假设数据框df,列df$subject, df$time, and df$conc,则

q <- sapply(c(low=0.05,med=0.50,high=0.95),
              function(x){by(df$conc,df$time,quantile,x)})

生成矩阵q,其中列lowmedhigh包含5%,50%和95%的分位数,每次一行。完整代码如下。

# generate some moderately realistic data
# concentration declines exponentially over time
# rate (k) is different for each subject and distributed as N[50,10]
# measurement error is distributed as N[1, 0.2]
time    <- 1:1000
df      <- data.frame(subject=rep(1:100, each=1000),time=rep(time,100))
k       <- rnorm(100,50,10)   # rate is different for each subject
df$conc <- 5*exp(-time/k[df$subject])+rnorm(100000,1,0.2)

# generates a matrix with columns low, med, and high 
q <- sapply(c(low=0.05,med=0.50,high=0.95),
            function(x){by(df$conc,df$time,quantile,x)})
# prepend time and convert to dataframe
q <- data.frame(time,q)
# plot the results
library(reshape2)
library(ggplot2)
gg <- melt(q, id.vars="time", variable.name="quantile", value.name="conc")
ggplot(gg) + 
  geom_line(aes(x=time, y=conc, color=quantile))+
  scale_color_discrete(labels=c("5%","50%","95%"))

答案 1 :(得分:0)

理想情况下,某些数据有助于确保但这应该有效:

a<-by(conc,time,quantile,0.05)

如果conc和time都在数据框中(称之为frame1):

a<-by(frame1$conc,frame1$time,quantile,probs=c(0.05,0.5))

答案 2 :(得分:0)

这是使用data.table的另一种方法。我不确定这是否是您正在寻找的,但一种选择是切割时间变量并使用cut()将其转换为3个类别(或您需要的),然后计算每个组的分位数。

定义你的功能

qt <- function(x) quantile(x, probs = c(0.05, 0.5, 0.95))

创建数据

DT <- data.table(time = sample(1:100, 100), blood_con = sample(500:1000, 100))
DT$cut_time <- cut(DT$time, right = FALSE, breaks = c(0, 30, 60, 10e5), 
                   labels = c("LOW", "MEDIUM", "HIGH"))

头(DT)

通过cut_time

将qt函数应用于所有列和组
Q <- DT[, list(blood_con = qt(blood_con)), by = cut_time]
Q$quantile_label <- as.factor(c("5%", "50%", "95%"))

剧情

ggplot(Q, (aes(x = cut_time, y = blood_con, label = quantile_label, color = quantile_label))) + 
  geom_point(size = 4) +
  geom_text(hjust = 1.5)