find out the unique elements in a vector

How to find out the unique elements in a vector


  R Interview Questions

For more R interview questions go here.

Say there are 100 students being graded

# Prepare some sample grades. 
> grades = round(rnorm(100,mean=3.5,sd=0.5),1)
> grades
  [1] 4.0 4.2 2.9 3.6 3.5 3.5 3.6 4.2 3.6 3.2 4.0 3.8 2.8 4.2
 [15] 3.2 4.1 3.8 3.4 3.1 4.2 3.5 2.8 3.5 4.2 3.2 3.0 3.2 3.4
 [29] 3.9 3.2 3.8 3.2 3.3 3.5 3.8 4.0 3.2 3.5 2.7 3.5 3.1 3.3
 [43] 3.8 3.9 4.0 3.8 4.7 2.9 2.6 3.8 4.1 3.1 3.7 4.1 3.7 2.4
 [57] 3.6 2.4 2.8 3.3 3.2 2.9 3.3 3.1 4.0 3.3 3.4 3.5 3.8 4.2
 [71] 3.4 3.3 2.3 3.5 3.5 4.1 4.2 3.7 4.3 2.7 3.7 4.5 3.2 3.3
 [85] 3.3 3.0 3.5 2.5 3.8 3.1 4.4 2.7 3.3 3.7 3.4 3.5 4.1 4.2
 [99] 3.7 4.2

and you want to find out how many unique grades there are.

UNIQUE () function

> unique(grades)
 [1] 4.0 4.2 2.9 3.6 3.5 3.2 3.8 2.8 4.1 3.4 3.1 3.0 3.9 3.3 2.7
[16] 4.7 2.6 3.7 2.4 2.3 4.3 4.5 2.5 4.4

TABLE () function

> table(grades)
grades
2.3 2.4 2.5 2.6 2.7 2.8 2.9   3 3.1 3.2 3.3 3.4 3.5 3.6 3.7 3.8 3.9   4 4.1 4.2 4.3 4.4 4.5 4.7 
  1   2   1   1   3   3   3   2   5   9   9   5  12   4   6   9   2   5   5   9   1   1   1   1
%d bloggers like this: