fill_NAs = function(file) { dat_with_date = read.csv(file) dat = dat_with_date[,-1] #get rid of date column line = 1 n = nrow(dat) p = ncol(dat) last_noNA_indices = rep(0, p) while (line <= n) { for (i in 1:p) { if (!is.na(dat[line,i])) { if (last_noNA_indices[i] < line-1) { #do some completion meanVal = ifelse( last_noNA_indices[i]>0, 0.5*(dat[last_noNA_indices[i],i]+dat[line,i]), dat[line,i] ) dat[(last_noNA_indices[i]+1):(line-1),i] = meanVal } last_noNA_indices[i] = line } } line = line + 1 } #complete until end if needed for (i in 1:p) { if (last_noNA_indices[i] < n) dat[(last_noNA_indices[i]+1):n,i] = dat[last_noNA_indices[i],i] } dat_with_date[,2:(p+1)] = dat write.csv(dat_with_date, "NONA.csv", row.names=FALSE) }