# TODO: Add comment
# 
# Author: E.Korsching  2016
###############################################################################


colMeansPerGroup <- function(x, gr){
	# colMeans of numeric columns, for rows which are deemed to be indentical based on a ID column
	# character values will be collapsed to one string
	# x: data.frame, processing column wise
	# gr: number of group column (needs to included in x)
	# rows with a 'NA' in the gr column will be discarded
	
	xnames <- names(x)
	dtypes <- unlist( lapply(x, is.numeric) )
	dpos <- which(dtypes)
	cat("\n numeric columns which will be considered for the colMean : ",dpos,"\n")
	dneg <- which(!dtypes)
	cat("\n other columns considered for 'collapsing' : ",dneg,"\n")
	ml <- length(c(dpos,dneg))
	df <- data.frame( matrix(0,1,ml) )
	names(df) <- xnames
	
	xa <- split(x, f=x[,gr])
	xa.len <- length(xa)
	
	f1 <- function(x){
		tmp <- paste( unique(x), collapse=" ")
	}
	f2 <- function(x,dpos,dneg){
		df <- data.frame( matrix(0,1,ml) )
		names(df) <- xnames
		if(nrow(x)>1){
			df[1,dpos] <- colMeans(x[ ,dpos], na.rm=T)
#			print(x[ ,dneg, drop=F])
			t.dneg <- apply(x[ ,dneg, drop=F], 2, f1)
			df[1,dneg] <- t.dneg
		}else{
			df <- x
		}
		return(df)
	}
#	tmp <- t( sapply(xa, f2, dpos=dpos, dneg=dneg) )		# problems with data types
#	tmp <- data.frame( apply(tmp, 2, unlist), stringsAsFactors=F)
	for(i in 1:xa.len){
		df <- rbind(df, f2(xa[[i]], dpos=dpos, dneg=dneg))
	}
	df <- df[-1,]
	return(df)
}

#colMeansPerGroup(x=p5.tma[1:10,], gr=1)



