Tuesday, August 8, 2017

which() {base}


which() function is a generic function that returns the position of a logical object.
The parameters of the function are: x: vector or array arr.ind: logical, to decide if the indices should be returned in an array ind: integer-valued index vector
x <- c(1,1,1,1,2)
x
## [1] 1 1 1 1 2
which(x == 2)
## [1] 5
summary(chickwts)
##      weight             feed   
##  Min.   :108.0   casein   :12  
##  1st Qu.:204.5   horsebean:10  
##  Median :258.0   linseed  :12  
##  Mean   :261.3   meatmeal :11  
##  3rd Qu.:323.5   soybean  :14  
##  Max.   :423.0   sunflower:12
which(chickwts$feed=='horsebean')
##  [1]  1  2  3  4  5  6  7  8  9 10
which(chickwts$feed=='soybean')
##  [1] 23 24 25 26 27 28 29 30 31 32 33 34 35 36
x <- matrix(c(2,3,2,3,1,1,1,1,2,3),ncol = 5)
x
##      [,1] [,2] [,3] [,4] [,5]
## [1,]    2    2    1    1    2
## [2,]    3    3    1    1    3
#which are the positions of the numbers multiple of 2. 
#the positions are counted by columns
#1 3 5 7 9
#2 4 6 8 10
which(x %% 2 == 0)   
## [1] 1 3 9
#which are the position of the numbers multiple of 2, it returns the array indices
which(x %% 2 == 0, arr.ind = TRUE) 
##      row col
## [1,]   1   1
## [2,]   1   2
## [3,]   1   5
which.min(x) #returns the first position of the minimum value that appears in the object. 
## [1] 5
which.max(x) #returns the first position of the maximum value that appears in the object. 
## [1] 2

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:   ...