From ccberry at ucsd.edu  Fri Jun 16 21:12:43 2017
From: ccberry at ucsd.edu (Charles C. Berry)
Date: Fri, 16 Jun 2017 12:12:43 -0700
Subject: [Rd] Simplify and By Convert Factors To Numeric Values
In-Reply-To: <DM5PR01MB32592033EEE2E8C8CC012DABCDC10@DM5PR01MB3259.prod.exchangelabs.com>
References: <DM5PR01MB32592033EEE2E8C8CC012DABCDC10@DM5PR01MB3259.prod.exchangelabs.com>
Message-ID: <alpine.OSX.2.20.1706161151530.996@charles-berrys-macbook.local>

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



[Rd] Simplify and By Convert Factors To Numeric Values
Charles C. Berry