[R] Incorrect Summarization after As.numeric
Sarah Goslee
sarah.goslee at gmail.com
Mon Dec 28 19:41:37 CET 2015
You probably want
as.numeric(as.character(myfactor))
since the underlying numeric representation of a factor that's
obtained with as.numeric() does not match what you see if your factor
"appears" numeric.
> myfactor <- as.factor(c("5", "6", "43", "22", "5", "22", "22"))
> myfactor
[1] 5 6 43 22 5 22 22
Levels: 22 43 5 6
> as.numeric(myfactor)
[1] 3 4 2 1 3 1 1
> as.numeric(as.character(myfactor))
[1] 5 6 43 22 5 22 22
One of the examples for ?as.numeric demonstrates this, but it's not
explicitly explained there.
Sarah
On Mon, Dec 28, 2015 at 1:32 PM, John Kane <jrkrideau at inbox.com> wrote:
> It would likely help to have some sample data. Please have a look at
> http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example and/or http://adv-r.had.co.nz/Reproducibility.html
>
> John Kane
> Kingston ON Canada
>
>
>> -----Original Message-----
>> From: shivi.bhatia at safexpress.com
>> Sent: Mon, 28 Dec 2015 14:42:03 +0530
>> To: r-help at r-project.org
>> Subject: [R] Incorrect Summarization after As.numeric
>>
>> Dear Team,
>>
>>
>>
>> I am working on aggregate function in R & have used the below code:
>>
>>
>>
>> aggregate(a1$Final,list(Year=a1$Year),sum)
>>
>>
>>
>> initially a1$Final was factor hence I used a1$Final= as.numeric(a1$Final)
>> to
>> convert this into numeric. After conversion it shows the output but the
>> summarization from the aggregate is incorrect. This I have reconciled
>> with
>> the excel pivot.
>>
>>
>>
>> Could you please suggest where could be the issue?
>>
>>
>>
>> Thanks, Shivi
>>
>> Mb: 9891002021
>>
>>
More information about the R-help
mailing list