Q:

sapply function(x) where x is subsetted argument

So, I want to generate a new vector from the information in two existing ones (numerical), one which sets the id for the participant, the other indicating the observation number. Each paticipant has been observed different times.
Now, the new vector should should state: 0 when obs_no=1; 1 when obs_no=last observation for that id; NA for cases in between. 
id   obs_no   new_vector
1    1        0
1    2        NA
1    3        NA
1    4        NA
1    5        1
2    1        0
2    2        1
3    1        0
3    2        NA
3    3        1

I figure I could do this separatly for every id using code like this
new_vector <- c(0, rep(NA, times=length(obs_no[id==1])-2), 1)

Or I guess just using max() but it wouldn't make any difference. 
But adding each participant manually is really inconvenient since I have a lot of cases. I can't figure out how to make a generic function. I tried to define a function(x) using sapply but cant get it to work since x is positioned within subsetting brackets.
Any advice would be helpful. Thanks. 

A:

ave to the rescue:
dat$newvar <- NA
dat$newvar <- with(dat,
  ave(newvar, id, FUN=function(x) replace(x, c(length(x),1), c(1,0)) ) 
)

Or use a bit of duplicated() fun:
dat$newvar <- NA
dat$newvar[!duplicated(dat$id, fromLast=TRUE)] <- 1
dat$newvar[!duplicated(dat$id)] <- 0

Both giving:
#   id obs_no new_vector newvar
#1   1      1          0      0
#2   1      2         NA     NA
#3   1      3         NA     NA
#4   1      4         NA     NA
#5   1      5          1      1
#6   2      1          0      0
#7   2      2          1      1
#8   3      1          0      0
#9   3      2         NA     NA
#10  3      3          1      1

