我有100个受试者的血药浓度和时间的数据。我对绘制5,50和95%分位数浓度对时间的曲线很感兴趣。虽然我可以确定整个浓度范围的分位数,但我无法在R中计算出如何按时间对浓度分位数进行分层。任何帮助都将不胜感激。
a<-quantile(conc~time, 0.05) 不起作用。
发布于 2013-12-31 07:40:56
假设数据帧为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%"))

发布于 2013-12-31 06:27:12
理想情况下,一些数据将有助于确保,但这应该是可行的:
a<-by(conc,time,quantile,0.05)如果conc和time都在数据帧中(称为frame1):
a<-by(frame1$conc,frame1$time,quantile,probs=c(0.05,0.5))发布于 2013-12-31 08:44:33
这是另一种使用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)https://stackoverflow.com/questions/20846560
复制相似问题