Hi, I have a matrix of data from from several groups. I need to center the data by group, subtracting the group median from each value, initially for two groups at a time. I have a working function to do this, but it looks quite inelegant. There must be a more straightforward way to do this, but I always get tangled up in apply/sweep/subset operations. Any suggestions welcome!
Thanks, Tyler My code: Notes: data.mat is an nxm matrix of data. group.vec is a vector of length n with grouping factors. group.sel is a vector of length 2 of the groups to include in the analysis. sweep.median <- function (data.mat, group.vec, group.sel) { data.sub1 <- data.mat[group.vec %in% group.sel[1],] data.sub2 <- data.mat[group.vec %in% group.sel[2],] data.sub1.med <- apply(data.sub1, MAR=2, median) data.sub1.cent <- sweep(data.sub1, MARGIN=2, data.sub1.med) data.sub2.med <- apply(data.sub2, MAR=2, median) data.sub2.cent <- sweep(data.sub2, MARGIN=2, data.sub2.med) data.comb <- rbind(data.sub1.cent, data.sub2.cent) data.comb <- cbind(c(rep(group.sel[1],nrow(data.sub1.cent)), rep(group.sel[2],nrow(data.sub2.cent))), data.comb) return(data.comb) } ______________________________________________ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.