I want to fill NA values in a sequence, which is row-wise, based on a condition. Please see example below.
ID | Observation 1 | Observation 2 | Observation 3 | Observation 4 | Observation 5
A NA 0 1 NA NA
The condition is:
- all NA values before !NA values in the sequence should be left as NA;
- but all NAs after !NA values in the sequence should be tagged ("remove")
In the example above, NA value in Observation 1 should remain NA. However, the NA values in Observations 4 and 5 should be changed to "Remove".
You can define the function:
Then, assuming that you have a
data.framelike so:We can
applythe function over the rows for all numeric columns ofr:This treats
r[,-1]as amatrixand the output ofapplyfills amatrix, which by default is filled by columns. Therefore, we have to transpose the resultingmatrixbefore replacing the columns back intor.Another way to call
replace.nais:Here, we transpose the numeric columns of
rfirst and make that adata.frame. This makes each row ofra column in the list of columns that is the resulting data frame. Then uselapplyover these columns to applyreplace.naandrbindthe results.If you want to flag all
NA's after the first non-NA, then the functionreplace.nashould be:Applying it to the data: