Q:

R: How to replace NA with specific year's value by ID?

Here is part of my dataset:
    ID year wf_income mrg_status mrg_tenure edu_wf
    2  1985     0       1       43       NA
    2  1986   3000      1       NA       NA
    2  1987   5200      1       NA       NA
    2  1988     0       1       NA       NA
    2  1989    360      1       NA        5
    3  1985    2600     1       18       NA
    3  1986    5365     1       NA       NA
    3  1987     0       1       NA       NA
    3  1988    5700     1       NA       NA
    3  1989     0       0       NA        9

What I want to do:

        for(i in ID), if "edu_wf" is NA, replace "edu_wf" with "edu_wf" record in 1989. For example, for ID = 1, replace edu_wf in 1985:1988 with 5
Thanks a lot!

A:

I think this is what you need for #1
df$edu_wf <- ifelse(is.NA(df$edu_wf), 1988, df$edu_wf)
Based on your clarification, I thin the following will work:
library(dplyr)

ID <- c(2,2,2,2,2,3,3,3,3,3)
year <- c(1985,1986,1987,1988,1989,1985,1986,1987,1988,1989)
edu_wf <- c(NA,NA,NA,NA,5,NA,NA,NA,NA,9)
df <- data.frame(ID, year,edu_wf)
fn <- function(x){ rep(na.omit(x),length(x)) }
df2 <- ddply(df, "ID", transform, edu_wf=fn(edu_wf))

df
df2

Produces:
> df
   ID year edu_wf
1   2 1985     NA
2   2 1986     NA
3   2 1987     NA
4   2 1988     NA
5   2 1989      5
6   3 1985     NA
7   3 1986     NA
8   3 1987     NA
9   3 1988     NA
10  3 1989      9
> df2
   ID year edu_wf
1   2 1985      5
2   2 1986      5
3   2 1987      5
4   2 1988      5
5   2 1989      5
6   3 1985      9
7   3 1986      9
8   3 1987      9
9   3 1988      9
10  3 1989      9

See the documentation on hadly's plyr package, particularly the split, apply, combine paradigm, for more information.

