# TODO: Add comment
# 
# Author: E.Korsching 19.12.2011, 30.03.2021
###############################################################################



replace.NA.rc <- function(x, rc="row", with="mean", fix){
	# replace NAs NaNs row/col wise
	# input: x: data.frame or matrix
	# rc: "row", "col"  wise replacement
	# with: "mean",  "median",  "fix"
	# fix: value
	
	#ini
	sum.na <- sum(is.na(x))
	nrx <- nrow(x)
	ncx <- ncol(x)
	
	# calculate replacement values
	if(rc=="row"){
		if(with=="mean") tmp <- apply(x, 1, mean, na.rm=T)
		if(with=="median") tmp <- apply(x, 1, median, na.rm=T)
		if(with=="fix") tmp <- rep(fix, nrx)
	}else{
		if(with=="mean") tmp <- apply(x, 2, mean, na.rm=T)
		if(with=="median") tmp <- apply(x, 2, median, na.rm=T)
		if(with=="fix") tmp <- rep(fix, ncx)
	}
	
	# replace NA
	if(rc=="row"){
		for(i in 1:nrx) {
			x[i, ] <- replace(x[i, ], is.na(x[i, ]), tmp[i])
		}
	}else{
		for(i in 1:ncx) {
			x[, i] <- replace(x[, i], is.na(x[, i]), tmp[i])
		}
	}
	
	cat(" NA before: ",sum.na," ,  NA after: ",sum(is.na(x)),"\n\n")
	return(x)
}



#matrix(c(1,2,3,NA,5,6,7,NA,9),3,3)
#replace.NA.rc(x=matrix(c(1,2,3,NA,5,6,7,NA,9),3,3), rc="row", with="mean")
#replace.NA.rc(x=matrix(c(1,2,3,NA,5,6,7,NA,9),3,3), rc="col", with="mean")
#replace.NA.rc(x=matrix(c(1,2,3,NA,5,6,7,NA,9),3,3), rc="col", with="fix", fix=1)



