Question: I'm having difficulties with some recoding (filling in empty cells in R or SPSS)

I'm working with a long format data-set (in order to run a multilevel model) where each respondent (ID-variable) has three rows, so three times the same ID number below each other (for three different momemts in time).

The problem is that for a second variable (ancestry of respondent) only the first row has a value but the two second rows for each respondent misses that (same) value (0/1). Can any one help? I'm only used to recoding within the same row... below a the data format. 

```
ID      Ancestry    
1003    1
1003    .
1003    .
1004    0
1004    .
1004    .
1005    1
1005    .
1005    .

```

Answer: 
We can use `na.locf` assuming that `.` implies `NA` values.

```
 library(zoo)
 df1$Ancestry <- na.locf(df1$Ancestry)

```

If the column is non-numeric i.e. have `.` as values, then we need to convert it to numeric so that the `.` coerce to NA and then we apply `na.locf` on it

```
 df1$Ancestry <- na.locf(as.numeric(df1$Ancestry))
 df1$Ancestry
 #[1] 1 1 1 0 0 0 1 1 1

```

If it needs to be grouped by "ID"

```
 library(data.table)
 setDT(df1)[, Ancestry := na.locf(Ancestry), by = ID]

```
Once you convert the `.`s to `NA` by your favorite method, this is exactly what `tidyr::fill` was designed to do:

```
library(tidyr)

df %>% extract(Ancestry, 'Ancestry', convert = TRUE) %>% fill(Ancestry)
# 
#     ID Ancestry
# 1 1003        1
# 2 1003        1
# 3 1003        1
# 4 1004        0
# 5 1004        0
# 6 1004        0
# 7 1005        1
# 8 1005        1
# 9 1005        1

```