In a dataframe I have a vector with some values, and vectors of categories that each value belongs to. I want to apply a function to the values, that operates "by category", so I use tapply. For example, in my case I want to rescale the values within each category.
However, the result of tapply is a list of vectors of the rescaled values, but I need to unify (or "linearize" back) this list, so I can add a column of the rescaled values to my data frame.
I'm looking for a simple way to do that. here is a sample:
x = 1:10
c = factor(c(1,2,1,2,1,2,1,2,1,2))
#I do the rescaling like this:
rescaled = tapply(x,list(c),function(x) as.vector(scale(x)))
# this look like this:
$`1`
[1] -1.2649111 -0.6324555 0.0000000 0.6324555 1.2649111
$`2`
[1] -1.2649111 -0.6324555 0.0000000 0.6324555 1.2649111
# but really, I need to get something like this
[1] -1.2649111 -1.2649111 -0.6324555 -0.6324555 0.0000000 0.0000000
[7] 0.6324555 0.6324555 1.2649111 1.2649111
Any suggestions?
thanks, amit