[R] Sweep for data frames?

Damon Wischik djw1005 at cam.ac.uk
Wed Jan 8 16:34:04 CET 2003

I am trying (I think) to achieve something like "sweep" for data frames.

I have a data frame. Two columns are factors, say with L and M levels; one
is numeric. Within each of L*M classes of observations, I would like to
normalize the numerical value by its mean.

Here is an example of what I mean.

data <- data.frame(
split.names <- c("fac1","fac2")
t <- tapply(data$x, data[split.names], mean)
# now t is an array, and I can index it like this:
# I want to do something like
data$xnorm <- data$x / t[data[split.names]]
# but I am told: Error: invalid subscript type

I would like to retrieve a vector of the values of the t-array, one item
in the vector for each row of the data frame. I would be grateful for

I think I could also achieve this by creating a data frame instead of the
table t, as in Venables+Ripley MASS (4th ed) p. 39, and then merging the
tables, as on p. 35. Is this the most effective way to achieve what I
want, or is there a more direct way?


More information about the R-help mailing list