I have a dataframe of 6 variables. For each column, data is same for the same group with some missing values. I want to fill these missing values by duplicating value of the same group for each variable. In case all values are missing for a particular group, it should fill value of above group. So, I want the result as df_complete.
Here is what I have tried but it fails when first observation of any group is missing. Unable to figure out what is wrong in it.
set.seed(123)
df <- data.frame(matrix(rnorm(100), ncol = 5))
df$Group <- letters[1:20]
df <- df[rep(seq_len(nrow(df)), sample(1:10, 20, replace = T)),]
df_complete <- df
df$X1[sample(1:nrow(df), 15)] <- NA
df$X2[sample(1:nrow(df), 10)] <- NA
df$X3[sample(1:nrow(df), 25)] <- NA
df$X4[sample(1:nrow(df), 10)] <- NA
df$X5[sample(1:nrow(df), 15)] <- NA
lvcf <- function(x)
{
miss_ind <- which(is.na(x))
if(length(miss_ind) != 0)
{
if(miss_ind[1]==1)
{
ind1 <- which(!is.na(x))[1]
x[1] <- x[ind1]
miss_ind <- which(is.na(x))
}
for(i in 1:length(miss_ind))
{
x[miss_ind[i]] <- x[miss_ind[i]-1]
}
}
return(x)
}
df_complete <- df %>%
group_by(Group) %>%
sapply(lvcf)