Sara
Sara

Reputation: 3

how to add an ordinal factor to the dataframe in r

I'm new here and new to r programming and hope that you can help me with:

I have the following code:

set.seed(1)
gender<-sample(c("M","F"),size=100,replace=TRUE)
mark<-round(rnorm(100,mean=55,sd=10),0)

How can I add an ordinal factor to my dataframe showing the grade A-E that each student has, where A=85-100, B=70-84, C=55-69, D=40- 54, E=25-39.

Many thanks for your kind help

Upvotes: 0

Views: 219

Answers (1)

Pierre L
Pierre L

Reputation: 28441

You can use cut to divide the scores into 5 bins. The labels argument allows you to provide the names of the groups.

The range of the bins will have the pattern, start < x <= end. That means the lowest is not included. Therefore a score of 25 will result in NA, so we make the argument include.lowest=TRUE:

cut(mark, c(25, 40, 55, 70, 85, 100), labels=rev(LETTERS[1:5]), include.lowest=TRUE)
#[1] C B C B C D B B C B D B C B B C A C C D..

Upvotes: 2

Related Questions