[R] Factor to Numeric

David Winsemius dwinsemius at comcast.net
Wed May 26 14:14:04 CEST 2010


On May 26, 2010, at 4:05 AM, Ivan Calandra wrote:

> What about (not tested because no sample data, and I'm definitely  
> unsure
> of my lapply() solution):
> lapply(data[2:13], FUN=as.character)
> lapply(data[2:13], FUN=as.numeric)
> ?
>

That would not preserve any of the output since no assignments were  
made. Consider instead:

data[ , -1] <- lapply(data[, -1] , function(x)  
as.numeric(as.character(x))  )

Would be safer to make a copy of "data" and work on it, and of course,  
there is always:

require(fortunes)
fortune("dog")

-- 
David.
> data[2:13] should correspond to the 12 Month columns.
> There might be a way to combine both lines but I don't think lapply
> would work with 2 function names.
>
> When I can't find a vectorized solution, or one with *apply, I use a  
> for
> loop. I find it very easy to understand and it's fast enough for my
> "small" datasets
>
> HTH
> Ivan
>
> Le 5/26/2010 09:57, Mohan L a écrit :
>>
>>
>> On Wed, May 26, 2010 at 1:13 PM, Ivan Calandra
>> <ivan.calandra at uni-hamburg.de <mailto:ivan.calandra at uni-hamburg.de>>
>> wrote:
>>
>>    Hi,
>>
>>    What about:
>>    as.numeric(as.character(data$State))
>>    ?
>>
>>
>> What I what is, I want to convert all the column excluding State to
>> factor to numeric in the data frame. So that  I will send  this data
>> frame to another function to total .
>>
>> Any help.
>>
>> Thanks & Rg
>> Mohan L
>>
>
> -- 
> Ivan CALANDRA
> PhD Student
> University of Hamburg
> Biozentrum Grindel und Zoologisches Museum
> Abt. Säugetiere
> Martin-Luther-King-Platz 3
> D-20146 Hamburg, GERMANY
> +49(0)40 42838 6231
> ivan.calandra at uni-hamburg.de
>
> **********
> http://www.for771.uni-bonn.de
> http://webapp5.rrz.uni-hamburg.de/mammals/eng/mitarbeiter.php
>
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list