Troubleshooting ddply() script
===

I am developing a censored dependent variable for use in survival analysis. My goal is to find the last time ("time") that someone answers a question in a survey (e.g. the point where "q.time" is coded as "1", and "q.time+1" and q at all subsequent times are coded as "0").  

By this logic, the last question answered should be coded as "1" (q.time). The first question that is NOT answered (q.time+1) should be coded as "0". And all questions subsequent to the first question NOT answered should be coded as "NA".  I then want to remove ALL rows where the DV=NA from my dataset.

A very generous coworker has helped me to develop the following code, but he's on vacation now and it needs a little more lovin'. Code is as follows:

    library(plyr)  # for ddply 
    library(reshape2)  # for reshape(...) 
    # From above 
    dat <- data.frame( 
      id=c(1, 2, 3, 4), 
      q.1=c(1, 1, 0, 0), 
      q.2=c(1, 0, 1, 0), 
      dv.1=c(1, 1, 1, 1), 
      dv.2=c(1, 1, 0, 1)) 
    # From above 
      long <- reshape(dat, 
                    direction='long', 
                    varying=c('q.1', 'q.2', 'dv.1', 'dv.2')) 
       ddply(long, .(id), function(df) { 
    # figure out the dropoff time 
    answered <- subset(df, q == 1) 
    last.q = max(answered$time) 
    subs <- subset(df, time <= last.q + 1) 
    # set all the dv as desired 
    new.dv <- rep(last.q,1) 
    if (last.q < max(df$time)) new.dv <- c(0,last.q) 
    subs$dv <- new.dv 
    subs 
    })

Unfortunately, this yields the error message:

    "Error in `$<-.data.frame`(`*tmp*`, "dv", value = c(0, -Inf)) : 
     replacement has 2 rows, data has 0"

Any ideas? The problem seems to be located in the "rep" command, but I'm a newbie to R. Thank you so much!
