Tuesday, October 24, 2017

unique() {base}


unique() function is a generic function that extracts unique values from a vector, array or data frame.

The parameters of the function are:
-x: vector, array or data frame to remove duplicated values
-fromLast: logical indicating if duplication should be considered from the last

#`unique()` function using vectors:
x = c(10 + 0:5, 1:5, 8:1)
x
##  [1] 10 11 12 13 14 15  1  2  3  4  5  8  7  6  5  4  3  2  1
u1 = unique(x)
u1
##  [1] 10 11 12 13 14 15  1  2  3  4  5  8  7  6
u2 = unique(x,  fromLast = TRUE) # different order
u2
##  [1] 10 11 12 13 14 15  8  7  6  5  4  3  2  1
y = c(5:1,8:1, 10, 1:3)
y
##  [1]  5  4  3  2  1  8  7  6  5  4  3  2  1 10  1  2  3
u3 = unique(y)
u3
## [1]  5  4  3  2  1  8  7  6 10
u4 = unique(y,  fromLast = TRUE) # different order
u4
## [1]  8  7  6  5  4 10  1  2  3
#`unique()` function with data frames:
dim(iris)
## [1] 150   5
nrow(unique(iris))
## [1] 149
unique(iris$Sepal.Width)
##  [1] 3.5 3.0 3.2 3.1 3.6 3.9 3.4 2.9 3.7 4.0 4.4 3.8 3.3 4.1 4.2 2.3 2.8
## [18] 2.4 2.7 2.0 2.2 2.5 2.6
length(unique(iris$Sepal.Width))
## [1] 23
par(mfrow = c(1,2))
plot(iris$Sepal.Length, col = 'darkturquoise',type = 'b', frame.plot = F)
plot(unique(iris$Sepal.Length), col = 'darkviolet',type='b', frame.plot = F)

No comments:

Post a Comment

duplicated() {base}

duplicated()  function determines which elements are duplicated and returns a logical vector. The parameters of the function are:   ...