2013-11-15 23 views
0

我已經從數個個體的單個可變(「計數‘)隨時間的縱向數據(’‘)(’ID」) ,以及一個代碼塊,它爲每個人生成一個單獨的圖表計數。在某些情況下,某些數據點在變量「Treat」下標記爲「1」,並繪製爲紅色。該有的都有款待值= 0添加坡多圖情節的子圖中的R

我的問題:我需要一個)迴歸線添加到每個情節,只使用有款待 = 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) 

思考大爲讚賞

+0

看一看'abline'?除了'reg'參數(在詳細信息部分中進行了解釋)之外,頁面底部還有一些示例說明如何將簡單迴歸線添加到圖中。 – BenBarnes

回答

0

只是輕微修改您的plot_one功能應該做的伎倆。

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)) 
    mod = lm(Count ~ Days, data = d[d$Treat == 0,]) 
    abline(reg = mod) 
    text(x=500, y=800, mod$coefficients[2]) 
} 

這給下面的圖(我改變了標準桿,使其大一點):

enter image description here

+0

這是一個很棒的解決方案,效果非常好。謝謝! – marcel