# TODO: Add comment
# 
# Author: E.Korsching Mar 15, 2012
###############################################################################


anova.ek <- function(x, categories, categ.ordered.n, group.label){
	# ANOVA (one way, independent samples, standard weighted-means analysis)
	#  nomenclature: "between/explained"  "within/unexplained/error"
	within.means <- NULL
	within.ss <- NULL
	between.ss <- NULL
	gr.len <- length(group.label)
	within.df2 <- sum(categ.ordered.n)-gr.len		# within group  degrees of freedoms
	between.df1 <- gr.len-1						# between group  degrees of freedoms
	for(i in 1:gr.len){
		m1 <- !is.na(match(x=categories, table=group.label[i]))			# select columns correponding to a group
		y <- x[m1]												# use only selected columns
		tmp1 <- mean(y)
		within.means <- cbind( within.means, tmp1 )			# means within groups
		tmp1 <- sum((y-tmp1)^2)
		within.ss <- cbind( within.ss, tmp1 )					# ss within groups
	}
	names(within.means) <- group.label		#name it (for fc loop in mtt)
	total.mean <- mean(within.means)			# total mean of all groups
	within.sse <- sum(within.ss)				# SSE : within-sample variance  or Mean Square Within or Mean Square Error
	for(i in 1:gr.len){
		tmp1 <- categ.ordered.n[i] * ((within.means[i]-total.mean)^2)
		between.ss <- cbind( between.ss, tmp1 )					# ss between groups
	}
	between.ssb <- sum(between.ss)				# SSB : between-sample variance  or Mean Square Between
	within.var <- within.sse/within.df2				# MSE/MSW Mean Square Within
	between.var <- between.ssb/between.df1				# MSB Mean Square Between
	f.value <- between.var/within.var			# F statistic : H0: means are equal: accept H0 if: F-Statistics < F-table or P-value > alpha
	fp.value <- 1 - pf(f.value, between.df1, within.df2) 		# lower.tail: probabilities are P[X ≤ x]
	
	#create result vector: fp.value, f.value, between.var, within.var, between.df1, within.df2, between.ssb, within.sse, within.means
	return( c(fp.value=fp.value,
					f.value=f.value,
					between.var=between.var,
					within.var=within.var,
					between.df1=between.df1,
					within.df2=within.df2,
					between.ssb=between.ssb,
					within.sse=within.sse,
					within.means=within.means
							)
	)
}



