[R] convert 400 numeric variables to categorical together

David L Carlson dcarlson at tamu.edu
Tue May 8 19:59:38 CEST 2012


Assuming the 400 numeric variables are integers this will be simpler if you
can identify the columns to be converted to factors as a block of column
numbers (e.g. 1:400, or 401:800)

# Create some data

X <- data.frame(matrix(nrow=20, ncol=20))
for (i in 1:10) X[,i] <- round(runif(20, .5, 5.5), 0)
for (i in 11:20) X[,i] <- rnorm(20)     
str(X) # structure of X

# convert numbers to factors for the first 10 columns

X2 <- X
for (i in 1:10) X2[,i] <- factor(X[,i])
str(X2)

----------------------------------------------
David L Carlson
Associate Professor of Anthropology
Texas A&M University
College Station, TX 77843-4352


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
> project.org] On Behalf Of ya
> Sent: Tuesday, May 08, 2012 12:01 PM
> To: r-help
> Subject: [R] convert 400 numeric variables to categorical together
> 
> 
> 
> 
> 
> 
> Hi Jim and Michael,
> 
> Thank you very much for replying.
> 
> Here is the information about my data. I have a data frame, including
> more than 800 variables(columns) and 30000 cases(rows).400 of those
> variables are categorical variables. I used to use Rcmdr to convert
> variables, however, when the number of variables I need to convert
> getting more, I need to keep left clicking mouse to confirm the
> conversion (400 times) because as.factor() can only convert 1 variable
> at a time. So I am thinking if there is any faster way. Thank you very
> much.
> 
> Best regards,
> 
> ya
> 
> 
> 
> ya
> 
> From: R. Michael Weylandt
> Date: 2012-05-08 19:35
> To: xinxi813
> CC: r-help
> Subject: Re: [R] convert 400 numeric variables to categorical together
> How are they arranged currently? And should they be all one set of
> levels or different factor sets?
> 
> Michael
> 
> On Tue, May 8, 2012 at 12:32 PM, ya <xinxi813 at 163.com> wrote:
> > Hi everyone,
> >
> > Is there anyway I can convert more than 400 numeric variables to
> categorical variables simultaneously?
> >
> > as.factor() is really slow, and only one at a time.
> >
> > Thank you very much.
> >
> > ya
> >        [[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.
> 	[[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.



More information about the R-help mailing list