Which function in R

March 3, 2017
By

(This article was first published on R – Greetz to Geeks, and kindly contributed to R-bloggers)

The which() function will return the position of the elements(i.e., row number/column number/array index) in a logical vector which are TRUE. Unlike the other base R functions, the which() will accept only the arguments with typeof as logical while the others will give an error.

Syntax: which(x, arr.ind = FALSE, useNames = TRUE)
                 arrayInd(ind, .dim, .dimnames = NULL, useNames = FALSE)

x: can be a logical vector or an array. NAs are treated as FALSE and  allowed. But they will be omitted
arr.ind: logical; should array indices be returned when x is an array?
ind: integer-valued index vector, as resulting from which(x)
.dim: integer vector
.dimnames: optional list of character dimnames(.), of which only .dimnames[[1]] is used
useNames: logical indicating if the value of arrayInd() should have (non-null) dimnames at all

Examples:

> which(letters == "g")
[1] 7
> x <- c(1,5,8,4,6)
> x
[1] 1 5 8 4 6
> which(x == 5)
[1] 2
> which(x != 5)
[1] 1 3 4 5
> datasets::npk
block N P K yield
1   1  0 1 1 49.5
2   1  1 1 0 62.8
3   1  0 0 0 46.8
4   1  1 0 1 57.0
5   2  1 0 0 59.8
6   2  1 1 1 58.5
7   2  0 0 1 55.5
8   2  0 1 0 56.0
9   3  0 1 0 62.8
10  3  1 1 1 55.8
11  3  1 0 0 69.5
12  3  0 0 1 55.0
13  4  1 0 0 62.0
14  4  1 1 1 48.8
15  4  0 0 1 45.5
16  4  0 1 0 44.2
17  5  1 1 0 52.0
18  5  0 0 0 51.5
19  5  1 0 1 49.8
20  5  0 1 1 48.8
21  6  1 0 1 57.2
22  6  1 1 0 59.0
23  6  0 1 1 53.2
24  6  0 0 0 56.0
> which(npk$yield == 62)
[1] 13
> which((npk$yield == 48.8) & (npk$N == 1))
[1] 14
which(npk$yield == max(npk$yield))
[1] 11
> x <- matrix(1:16,4,4)
> x
[,1] [,2] [,3] [,4]
[1,]  1    5   9    13
[2,]  2    6  10    14
[3,]  3    7  11    15
[4,]  4    8  12    16
> which.min(x)
[1] 1
> which.max(x)
[1] 16
> which(x %% 2 == 0)
[1] 2 4 6 8 10 12 14 16
> which(x %% 2 == 0, arr.ind=TRUE)
row col
[1,] 2 1
[2,] 4 1
[3,] 2 2
[4,] 4 2
[5,] 2 3
[6,] 4 3
[7,] 2 4
[8,] 4 4
> which(x %% 2 == 0, arr.ind=TRUE, useNames = FALSE)
[,1] [,2]
[1,] 2   1
[2,] 4   1
[3,] 2   2
[4,] 4   2
[5,] 2   3
[6,] 4   3
[7,] 2   4
[8,] 4   4

 

To leave a comment for the author, please follow the link and comment on their blog: R – Greetz to Geeks.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Search R-bloggers


Sponsors

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)