[Rd] Simplify and By Convert Factors To Numeric Values
Charles C. Berry
ccberry at ucsd.edu
Fri Jun 16 21:12:43 CEST 2017
On Fri, 16 Jun 2017, Dario Strbenac wrote:
> Good day,
>
> It's not described anywhere in the help page, but tapply and by
> functions will, by default, convert factors into numeric values. Perhaps
> this needs to be documented or the behaviour changed.
It *is* described in the help page.
This returns a list of objects and each object class has "factor"
tapply(rep(1:2,2), rep(1:2,2),
function(x) factor(LETTERS[x], levels = LETTERS))
and this
>
>> tapply(1:3, 1:3, function(x) factor(LETTERS[x], levels = LETTERS))
> 1 2 3
> 1 2 3
returns a vector object with no class.
>
> The documentation states "... tapply returns a multi-way array
> containing the values ..." but doesn't mention anything about converting
> factors into integers. I'd expect the values to be of the same type.
and also states
"If FUN returns a single atomic value for each such cell ... and when
simplify is TRUE ... if the return value has a class (e.g., an object of
class "Date") the class is discarded."
which is what just happened in your example.
Maybe you want:
unlist(tapply(1:3, 1:3, function(x) factor(LETTERS[x],
levels = LETTERS),simplify=FALSE))
Trying to preserve class worked here in a way you might have
hoped/expected, but might lead to difficulties in other uses.
HTH,
Chuck
More information about the R-devel
mailing list