[R] my ugly apply/sweep code needs help

Tyler Smith tyler.smith at mail.mcgill.ca
Sat May 19 01:46:50 CEST 2007


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!



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)),


More information about the R-help mailing list