[R] Create a categorical variable from numeric column

arun smartpink111 at yahoo.com
Sun Oct 6 15:29:06 CEST 2013




Hi,

I created 3 categories. If 1-7 and 18-24 should come under the same category, then:
 Categ<- findInterval(dat1$Col1,c(8,18))+1
Categ[Categ>2]<- 1
dat1$Categ<- Categ
 tail(dat1)
#   Col1       Col2 Categ
#45    2 -0.5419758     1
#46   21  1.1042719     1
#47   24 -1.0787079     1
#48   18  0.6253085     1
#49   15 -1.6822411     2
#50   16 -0.5966446     2

A.K.





----- Original Message -----
From: arun <smartpink111 at yahoo.com>
To: R help <r-help at r-project.org>
Cc: 
Sent: Saturday, October 5, 2013 8:30 PM
Subject: Re: Create a categorical variable from numeric column

Hi,
Try:
set.seed(29)
dat1<- data.frame(Col1=sample(1:24,50,replace=TRUE),Col2=rnorm(50))
 dat1$Categ <- findInterval(dat1$Col1,c(8,18))+1
  head(dat1)
#  Col1        Col2 Categ
#1    3 -0.09381378     1
#2    6 -0.83640257     1
#3    3  0.00307641     1
#4    8  0.04197496     2
#5   15  0.15433872     2
#6    3 -0.21301893     1

split(dat1,dat1$Categ)


A.K.


I  have a data frame that contains a numerical variable ranging from 1 to 24. I would like to create a new category with two ranges: 1 to 7 
and 18 to 24 will form one category and 8 to 17 will form another. How 
can I create this category? 

Thanks



More information about the R-help mailing list