[R] Convert a factor to a numeric

arun smartpink111 at yahoo.com
Thu Oct 10 15:02:52 CEST 2013


Hi,
It is not clear whether all the variables are factor or only a few are..

dat<- read.table(text="a                coef               coef.l              coef.h
1   1   0.005657825001254  0.00300612956318132 0.00830952043932667
2   2 0.00634505314577229  0.00334102345418614 0.00934908283735844
3   3 0.00368668099805019 0.000289702228748421 0.00708365976735195
4   4  0.0056200291035751  0.00209123538827368 0.00914882281887651
5   5 0.00636609791030242  0.00269683889899591  0.0100353569216089",sep="",colClasses=rep("factor",4)) 
dat1<- dat


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

str(dat)
#'data.frame':    5 obs. of  4 variables:
# $ a     : num  1 2 3 4 5
# $ coef  : num  0.00566 0.00635 0.00369 0.00562 0.00637
# $ coef.l: num  0.00301 0.00334 0.00029 0.00209 0.0027
# $ coef.h: num  0.00831 0.00935 0.00708 0.00915 0.01004


# With only a subset of variables in the dataset as factors
 dat1$a<- as.numeric(as.character(dat1$a))

 
dat1[sapply(dat1,is.factor)]<- lapply(dat1[sapply(dat1,is.factor)],function(x) as.numeric(as.character(x)))
 str(dat1)
#'data.frame':    5 obs. of  4 variables:
# $ a     : num  1 2 3 4 5
# $ coef  : num  0.00566 0.00635 0.00369 0.00562 0.00637
# $ coef.l: num  0.00301 0.00334 0.00029 0.00209 0.0027
# $ coef.h: num  0.00831 0.00935 0.00708 0.00915 0.01004
 
A.K.



I have a factor data frame which I want to convert to numeric without any change in contents. How could I do that? 


   a                coef               coef.l              coef.h 
1   1   0.005657825001254  0.00300612956318132 0.00830952043932667 
2   2 0.00634505314577229  0.00334102345418614 0.00934908283735844 
3   3 0.00368668099805019 0.000289702228748421 0.00708365976735195 
4   4  0.0056200291035751  0.00209123538827368 0.00914882281887651 
5   5 0.00636609791030242  0.00269683889899591  0.0100353569216089



More information about the R-help mailing list