Saturday 15 January 2011

statistics - r last observation carried forward unless no further observations -



statistics - r last observation carried forward unless no further observations -

i have info set takes serial temperature measurements several patients. dataset patchy , contains many na values. however, patients may have died before end of experiment , hence had nas recorded time of death until end of measurement period. want go through dataframe rows (individual patients) carrying lastly observation forwards unless there no farther observations recorded. little illustration dataframe be:

df<-data.frame(h0=c(35.4, 36.0, 36.0, 36.4), h1=c(na, 34.0, 33.4, na), h2=c(na, 33.5, na, 34.2), h3=c(32.9, na, 34.0, na), h4=c(na, 33.1, na, na), h5=c(33.2, na, na, 32.8))

i have kind of got working zoo , apply with:

df2<-apply(df, 1, na.locf)

although creates matrix , not dataframe, , carries temperature forwards dead patient until end of experiment, not want do. patients 2 & 3 should both still end in h5 na.

transpose, utilize na.fill fill in trailinig nas 0 , utilize na.locf fill in remaining nas , transpose back. replace zeros nas:

library(zoo) df0 <- t(na.locf(na.fill(t(df), c(na, na, 0)))) ifelse(df0 == 0, na, df0)

giving:

[,1] [,2] [,3] [,4] [,5] [,6] [1,] 35.4 35.4 35.4 32.9 32.9 33.2 [2,] 36.0 34.0 33.5 33.5 33.1 na [3,] 36.0 33.4 33.4 34.0 na na [4,] 36.4 36.4 34.2 34.2 34.2 32.8

it alternatively written this:

zero2na <- function(x) ifelse(x == 0, na, x) t(apply(df, 1, function(x) zero2na( na.locf( na.fill(x, c(na, na, 0))))))

r statistics zoo

No comments:

Post a Comment