R convert numeric variable to factor

64 views Asked by At

UPDATE I found solution to my problem, following code gives me correct answer

animaldata$myfac <- with(animaldata, recode(Age.Intake, "lo:0=1; 1:hi=2; else=2"))
animaldata$myfac = factor(animaldata$myfac)
levels(animaldata$myfac) <- list(young = 1, adult = 2)
table(animaldata$myfac)

young adult 
  191   282 

This question is not a duplicate of there other question using cut

I am trying to convert a numerical variable to a factor based of condition on that variable. But I am unable to do so.

## load the librray
library(SDSFoundations) 

## load the datset
animaldata <- AnimalData

# Get age of each gender
table(animaldata$Sex , animaldata$Age.Intake)

Running the above command gives the following result

           0   1   2   3   4   5   6   7   8   9  10  11  12  13  15  17
  Female  84  30  31  17  11  18   3   3   8   5   2   1   2   3   2   0
  Male   107  33  32  21  11  14  10  10   3   3   3   2   1   2   0   1

I want to create a factor variable Age with 2 levels using the following conditions

If animaldata$Age.Intake < 1 then young
else adult

I have tried using cut but got in correct result

table(cut(animaldata$Age.Intake,breaks = c(0, 1, Inf), labels = c("young", "adult")))

young adult 
   63   219 

UPDATE 2 I tried include.lowest = TRUE but I am still getting incorrect result.

table(cut(animaldata$Age.Intake,breaks = c(0, 1, Inf), labels = c("young", "adult"),include.lowest = TRUE))

young =254 and adult= 219
0

There are 0 answers