BenjyTec
BenjyTec

Reputation: 10333

Get next level from a given level factor

I am currently making my first steps using R with RStudio and right now I am struggling with the following problem: I got some test data about a marathon with four columns, where the third column is a factor with 15 levels representing different age classes. One age class randomAgeClass will be randomly selected at the beginning, and an object is created holding the data that matches this age class.

set.seed(12345678)
attach(marathon)
randomAgeClass <- sample(levels(marathon[,3]), 1)
filteredMara <- subset(marathon, AgeClass == randomAgeClass)

My goal is to store a second object that holds the data matching the next higher level, meaning that if age class 'kids' was randomly selected, I now want to access the data relating to 'teenagers', which is the next higher level. Looking something like this:

nextAgeClass <- .... randomAgeClass+1 .... ?
filteredMaraAgeClass <- subset(marathon, AgeClass == nextAgeClass)

Note that I already found this StackOverflow question, which seems to partially match my situation, but the accepted answer is not understandable to me, thus I wasn't able to apply it to my needs.

Thanks a lot for any patient help!

Upvotes: 0

Views: 56

Answers (1)

mfalco
mfalco

Reputation: 450

First you have to make sure thar the levels of your factor are ordered by age:

factor(marathon$AgeClass,levels=c("kids","teenagers",etc.))

Then you almost got there in your example:

next_pos<-which(levels(marathon$AgeClass)==randomAgeClass)+1 #here you get the desired position in the level vector
nextAgeClass <- levels(marathon$AgeClass) [next_pos]
filteredMaraAgeClass <- subset(marathon, AgeClass == nextAgeClass)

You might have a problem if the randomAgeClass is the last one, so make sure to avoid that problem

Upvotes: 1

Related Questions