[R] How do I convert factors to numeric? It's an FAQ but...

Milan Bouchet-Valat nalimilan at club.fr
Fri Apr 13 15:28:04 CEST 2012


Le vendredi 13 avril 2012 à 13:08 +0000, John Coulthard a écrit :
> Dear R list people
> 
> I loaded a file of numbers into R and got a dataframe of factors.  So I tried to convert it to numeric as per the FAQ using as.numeric().  But I'm getting errors (please see example), so what am I getting wrong?
> 
> Thanks for your time.
> John
> 
> Example...
> 
> #my data object
> > f
>    GSM187153 GSM187154 GSM187155 GSM187156 GSM187157 GSM187158 GSM187159
> 13  7.199346  7.394519  7.466155  8.035864  7.438536  7.308401  7.707994
> 14  6.910426  6.360291  6.228221   7.42918  7.120322  6.108129  7.201477
> 15   8.85921  9.152096  9.125067    6.4458  8.600319   8.97577  9.691167
> 16  5.851665  5.621529  5.673689  6.331274  6.160159   5.65945  5.595156
> 17  9.905257  8.596643   9.11741  9.872789  8.909299  9.104171  9.158998
> 18  6.176691  6.429807  6.418132  6.849236  6.162308  6.432743  6.444664
> 19  7.599871  8.795133  8.382509  5.887119  7.941895  7.666692  8.170374
> 20  9.458262   8.39701  8.402015    9.0859  8.995632  8.427601  8.265105
> 21  8.179803  9.868286 10.570601  4.905013  9.488779  9.148336  9.654022
> 22  7.456822  8.037138  7.953766  6.666418  7.674927  7.995109  7.635158
>    GSM187160 GSM187161 GSM187162
> 13  7.269558  7.537711  7.099806
> 14   6.61534  7.125821  6.413295
> 15   8.64715  8.252031  9.445682
> 16  5.639816    5.9257  5.752994
> 17  8.856829  9.043991  8.839183
> 18    6.4307   6.71052    6.5269
> 19  7.674577  7.390617  8.638025
> 20  8.132649  8.755642  8.137992
> 21  9.897561  7.619129 10.242096
> 22  7.836658  7.297986  8.679438
> > class(f)
> [1] "data.frame"
> 
> #all the columns in the dataframe are of class 'factor'
> > for(i in 1:ncol(f)){if(class(f[,i])!="factor"){print(class(f[,i]))}}
> >
> #but it won't convert to numeric
> > g<-as.numeric(as.character(f))
> Warning message:
> NAs introduced by coercion 
> > g
>  [1] NA NA NA NA NA NA NA NA NA NA
> > g<-as.numeric(levels(f))[as.integer(f)]
> Error: (list) object cannot be coerced to type 'integer'
That's because you're trying to convert the whole data frame, which is a
list of vectors, instead of converting the vectors individually. You can
use:
g <- sapply(f, function(x) as.numeric(as.character(x)))

But it would probably be better to fix the import step so that you get
numeric vectors in the first place. ;-)


Cheers



More information about the R-help mailing list