[R] sweep by levels of a factor

David Winsemius dwinsemius at comcast.net
Thu Nov 18 21:28:00 CET 2010


On Nov 18, 2010, at 1:23 PM, Henrique Dallazuanna wrote:

> Try this also:
>
> x$x - ave(x$x, x$f)

Could also use scale for only its centering capacities:

unlist(
    tapply(fx$x, fx$f, scale, scale=FALSE) # default for center == TRUE
        )
11 12 21 22 23
  1 -1 -2  2  0

... but looking at the code for ave and for tapply makes me think ave  
would win in a foot race. scale() has other capacities that make its  
availability useful.

-- 
David.

>
> On Thu, Nov 18, 2010 at 12:02 PM, Lancaster, Anthony <
> anthony_lancaster at brown.edu> wrote:
>
>> Hi,
>> I'd appreciate help with this. I have a data matrix with one  
>> column, called
>> f in the example below, a factor. I'd like to subtract the means  
>> from each
>> of
>> other columns for each level of the factor. That is, in the  
>> example, to go
>> from the first matrix below to the second. I know SWEEP will take out
>> means,
>> but I want to do this for each level of the factor.
>>     f    x
>>    1   2
>>    1   0
>>     2   0
>>     2   4
>>     2   2
>>
>>    f   xnew
>>    1    1
>>    1   -1
>>    2   -2
>>    2    2
>>    2     0
>> Thanks
>>
>>       [[alternative HTML version deleted]]
>>

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list