Hello, I have the following dataset:

clear
input year id value
1990 1 .
1991 1 .
1992 1 4
1993 1 .
1994 1 .
1995 1 8
1996 1 .
1997 1 .
1990 2 .
1991 2 2
1992 2 .
1993 2 .
1994 2 .
1995 2 6
1996 2 .
1997 2 .
end

I would like to replace the missing values in three ways:
  1. Sorted by id and year, I would like to replace the first missing values with the first non-missing value.
  2. Sorted by id and year, I would like to replace the missing values that are enclosed by two non-missing values with the average of these two non-missing values.
  3. Sorted by id and year, I would like to replace the last missing values with the last non-missing value.
The output dataset should look like this:

clear
input year id value
1990 1 4
1991 1 4
1992 1 4
1993 1 6
1994 1 6
1995 1 8
1996 1 8
1997 1 8
1990 2 2
1991 2 2
1992 2 4
1993 2 4
1994 2 4
1995 2 6
1996 2 6
1997 2 6
end

Thank you.