【问题标题】:Quantiles on Continuous Time Data连续时间数据的分位数
【发布时间】:2014-01-17 18:04:24
【问题描述】:

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

a<-quantile(conc~time, 0.05) 

不工作。

【问题讨论】:

  • 什么不起作用?能否提供一些示例数据?

标签: r plot continuous quantile


【解决方案1】:

这是使用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)

对所有列应用qt函数并按cut_time分组

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)

【讨论】:

    【解决方案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%"))
    

    【讨论】:

      【解决方案3】:

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

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

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

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

      【讨论】:

        猜你喜欢
        • 2017-08-26
        • 1970-01-01
        • 2017-01-13
        • 2020-08-19
        • 1970-01-01
        • 2023-02-26
        • 1970-01-01
        • 1970-01-01
        • 2017-11-15
        相关资源
        最近更新 更多