【发布时间】:2023-03-15 18:55:01
【问题描述】:
我有来自多个个体(“ID”)的单个变量(“Count”)与时间(“Days”)的纵向数据>),以及一段代码,它为每个人生成一个单独的 Count 图表。在某些情况下,一些数据点在变量“Treat”下标记为“1”,并以红色绘制。其他的有 Treat 值 = 0。
我的问题:我需要 a) 为每个图添加一条回归线,仅使用 Treat = 0 的数据点,并且 b) 需要在每个子图上打印线的斜率.我不知道该怎么做。到目前为止我的代码:
#plot longitudinal CD4 counts from multiple individuals in separate plots
#Clear work area
rm(list = ls(all = TRUE))
#Enter example data
tC <- textConnection("
ID VisitDate Count Treat Treatstarted
C0098 12-Feb-10 457 0 NA
C0098 2-Jul-10 467 0 NA
C0098 7-Oct-10 420 0 NA
C0098 3-Feb-11 357 0 NA
C0098 8-Jun-11 209 0 NA
C0098 9-Jul-11 223 0 NA
C0098 12-Oct-11 309 0 NA
C0110 23-Jun-10 629 0 30-Oct-10
C0110 30-Sep-10 461 0 30-Oct-10
C0110 15-Feb-11 270 1 30-Oct-10
C0110 22-Jun-11 236 1 30-Oct-10
C0151 2-Feb-10 199 0 NA
C0151 24-Mar-10 936 0 3-Apr-10
C0151 7-Jul-10 1147 1 3-Apr-10
C0151 9-Mar-11 1192 1 3-Apr-10
")
data1 <- read.table(header=TRUE, tC)
close.connection(tC)
# calculate elapsed time from first date, by ID
data1$VisitDate <- with(data1,as.Date(VisitDate,format="%d-%b-%y"))
data1$Days <- unlist(with(data1,tapply(VisitDate,ID,function(x){x-x[1]})))
#Define plot function
plot_one <- function(d){
with(d, plot(Days, Count, t="n", tck=1, main=unique(d$ID), cex.main = 0.8, ylab = "", yaxt = 'n', xlab = "", xaxt="n", xlim=c(0,1000), ylim=c(0,1200))) # set limits
grid(lwd = 0.3, lty = 7)
with(d[d$Treat == 0,], points(Days, Count, col = 1))
with(d[d$Treat == 1,], points(Days, Count, col = 2))
}
#Create multiple plot figure
par(mfrow=c(8,8), oma = c(0.5,0.5,0.5,0.5), mar = c(0.5,0.5,0.5,0.5))
plyr::d_ply(data1, "ID", plot_one)
非常感谢您的想法
【问题讨论】:
-
看看
?abline。除了reg参数(在详细信息部分中进行了说明)之外,页面底部附近还有一些示例,说明了如何向绘图添加简单的回归线。
标签: r