[R] Change Selected Variables from Numeric to Factors

arun smartpink111 at yahoo.com
Fri May 3 19:08:21 CEST 2013


Hi ST,
Try this:
set.seed(51)
df1<- as.data.frame(matrix(sample(1:40,60,replace=TRUE),ncol=10))
df2<- df1
check<- c("V3","V7","V9")
 df1[,match(check,colnames(df1))]<-lapply(df1[,match(check,colnames(df1))],as.factor)

str(df1)
#'data.frame':    6 obs. of  10 variables:
# $ V1 : int  32 9 12 40 9 34
# $ V2 : int  31 17 39 5 21 28
# $ V3 : Factor w/ 6 levels "1","6","7","10",..: 3 5 1 6 2 4
# $ V4 : int  26 4 8 18 39 2
# $ V5 : int  39 21 4 26 6 21
# $ V6 : int  27 33 35 8 17 8
# $ V7 : Factor w/ 5 levels "4","8","9","24",..: 2 3 4 1 3 5
# $ V8 : int  4 12 12 32 13 37
# $ V9 : Factor w/ 5 levels "10","31","33",..: 1 4 2 3 5 5
# $ V10: int  13 26 20 22 14 5

#or
 df2[check]<- lapply(check,function(x) as.factor(df2[[x]]))
# str(df2)
#'data.frame':    6 obs. of  10 variables:
# $ V1 : int  32 9 12 40 9 34
# $ V2 : int  31 17 39 5 21 28
# $ V3 : Factor w/ 6 levels "1","6","7","10",..: 3 5 1 6 2 4
# $ V4 : int  26 4 8 18 39 2
# $ V5 : int  39 21 4 26 6 21
# $ V6 : int  27 33 35 8 17 8
# $ V7 : Factor w/ 5 levels "4","8","9","24",..: 2 3 4 1 3 5
# $ V8 : int  4 12 12 32 13 37
# $ V9 : Factor w/ 5 levels "10","31","33",..: 1 4 2 3 5 5
# $ V10: int  13 26 20 22 14 5


A.K.

>I have a dataframe df with several columns. I need to change some of 
these to factors. What colums I need to change to factors is in another 
vector >check. 
>I am using this command 
>sapply(check , function(x) df[[x]] <- as.factor(df[[x]])) 
>
>But this is not working. Can someone please advise. 
>
>Thanks. 
>-ST



More information about the R-help mailing list