我有 100 名受试者的血液浓度与时间的关系数据。我有兴趣绘制 5%、50% 和 95% 的分位数浓度与时间曲线。虽然我可以确定整个浓度范围的分位数,但我无法在 R 中弄清楚如何按时间对浓度分位数进行分层。任何帮助,将不胜感激。
a<-quantile(conc~time, 0.05)
不起作用。
我有 100 名受试者的血液浓度与时间的关系数据。我有兴趣绘制 5%、50% 和 95% 的分位数浓度与时间曲线。虽然我可以确定整个浓度范围的分位数,但我无法在 R 中弄清楚如何按时间对浓度分位数进行分层。任何帮助,将不胜感激。
a<-quantile(conc~time, 0.05)
不起作用。
假设一个数据框 , 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
列low
, med
, 并high
包含 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%"))
这是另一种使用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)
理想情况下,一些数据将有助于确保,但这应该有效:
a<-by(conc,time,quantile,0.05)
如果 conc 和 time 都在数据框中(称为 frame1):
a<-by(frame1$conc,frame1$time,quantile,probs=c(0.05,0.5))