Written and maintained by CASRAI Editorial Board
Published · Last updated
On this page
The which() function in R identifies the integer indices or coordinates of elements within a logical vector, matrix, or array that evaluate to TRUE. Rather than returning the data values themselves, which() isolates their positional indices, systematically omitting NA values and providing optional multi-dimensional subscripts through the arr.ind parameter for structured statistical filtering, cohort selection, and matrix manipulation.
What it is used for in research
In quantitative empirical research, data analysis rarely consists of simple unconditional operations. Analysts frequently need to locate specific observational units, isolate experimental cohorts, replace corrupted instrument readings, and track coordinate positions across complex multidimensional arrays. The which() function provides the primary mechanism in base R for converting logical conditions into explicit numerical subscripts.
A primary research application is conditional cohort identification. In clinical trials, epidemiological surveys, and demographic panels, participants must often be stratified by criteria such as age thresholds, baseline diagnostic markers, or treatment adherence. When working with tabular data structures like data frames in R, researchers often need the exact row numbers where experimental criteria are met. Knowing the explicit index positions enables researchers to cross-reference multiple parallel measurements, align biomarker vectors with patient metadata, and verify data hygiene before fitting linear or generalized linear models.
Quality assurance and outlier screening represent another critical research use case. During laboratory data intake, sensor feeds or automated assays frequently generate extreme values, negative control failures, or unexpected machine errors. Using which(), an analyst can quickly identify the exact observations where readings violate physical laws or calibration tolerances. For example, identifying the observation rows where temperature exceeds 100 degrees Celsius or where gene expression readings fall below background noise levels allows targeted data audits, data cleaning, or flagging without discarding entire experimental records prematurely.
In spatial analysis, neuroimaging, and multidimensional signal processing, data often arrive stored in matrices or high-dimensional arrays rather than flat tables. When analyzing fMRI voxel activations or gridded climate temperature grids, scientists must determine not merely whether a threshold was crossed, but precisely where in the two-dimensional or three-dimensional coordinate system that threshold was exceeded. By setting the array indexing argument arr.ind = TRUE, which() transforms a boolean evaluation into a coordinate matrix of row and column subscripts, allowing spatial analysts to immediately map activated regions back to anatomic coordinates or geographical grids.
Positional indexing also plays a vital role in programmatic algorithm design, including iterative optimization routines, custom resampling loops, and discrete Markov chain simulations. In these mathematical contexts, an algorithm must know the exact memory position of a state transition or boundary condition to update transition probability matrices. Direct boolean indexing provides a subset of data values, but algorithm logic frequently requires the index integer itself to compute step distances, lag intervals, or dynamic window boundaries.
How to install or access it
The which() function is a core component of the R runtime environment. It is housed in the standard base package, which is maintained directly by the R Core Team and loaded automatically upon initialization in every R session. No external library installations, package downloads from CRAN, or GitHub compilations are required to access which(), which.min(), or which.max().
To access R and its base functional suite, researchers download official pre-compiled binary distributions or source code directly from the Comprehensive R Archive Network (CRAN) at https://cran.r-project.org/. CRAN provides officially verified releases for Linux, macOS, and Windows operating systems. The R Project distributes releases under the GNU General Public License, ensuring completely free, reproducible, and vendor-neutral access across academic institutions, government agencies, and private laboratories.
To verify that R is correctly installed and inspect the active session environment, launch the R command-line console, RStudio, or your preferred development environment, and execute the following commands:
# Check R version and active runtime environment
sessionInfo()
# Verify the documentation and signature of the which function
help(which, package = "base")
The R help system opens the official documentation manual for the which function, confirming its formal signature, package origin in package:base, and argument definitions. Understanding how which() operates on underlying atomic storage vectors is closely connected to mastering fundamental R data types, such as logical, integer, double, and character structures.
Step-by-step task
Executing conditional indexing with which() involves a disciplined sequence of steps, moving from single-condition vector evaluation to multidimensional array subscripting and extreme value extraction. Follow these documented procedures to implement which() accurately in research scripts.
Step 1: Construct a logical evaluation vector
The first argument to which() must be an expression or object that evaluates to a logical vector or array containing TRUE, FALSE, or NA values. In R, comparison operators such as ==, !=, >=, <=, and membership operators like %in% evaluate element-wise across vectors:
# Sample empirical measurement vector
cholesterol = c(185, 240, 210, 195, 265, 220)
# Evaluate a logical condition
high_risk = (cholesterol >= 220)
print(high_risk)
# Output: [1] FALSE TRUE FALSE FALSE TRUE TRUE
Step 2: Extract 1D integer indices using which()
Pass the logical condition to which() to extract the numerical positions where the condition evaluates to TRUE:
# Locate index positions of high-risk measurements
risk_indices = which(cholesterol >= 220)
print(risk_indices)
# Output: [1] 2 5 6
The returned integer vector confirms that the second, fifth, and sixth elements in cholesterol satisfy the criterion. You can immediately use these indices to subset the original vector, an associated patient identifier vector, or rows of a corresponding data frame.
Step 3: Preserve vector names using useNames
By default, which() includes the useNames = TRUE argument. If your input vector possesses named elements, which() preserves those character names alongside the returned integer positions:
# Named vector of patient IDs
patient_chol = c(PT01 = 185, PT02 = 240, PT03 = 210, PT04 = 195, PT05 = 265, PT06 = 220)
# Identify positions while retaining labels
flagged_pts = which(patient_chol >= 220)
print(flagged_pts)
# Output:
# PT02 PT05 PT06
# 2 5 6
# Explicitly suppress names if only raw integer indices are desired
unnamed_indices = which(patient_chol >= 220, useNames = FALSE)
print(unnamed_indices)
# Output: [1] 2 5 6
Step 4: Extract matrix coordinates using arr.ind = TRUE
When analyzing two-dimensional matrices, covariance tables, or high-dimensional arrays, linear integer indices are often insufficient because analysts need specific row and column subscripts. Setting arr.ind = TRUE forces which() to return a structured two-column integer matrix indicating the exact row and column coordinates of every matching cell. This technique is particularly valuable when inspecting correlation structures or conducting matrix operations in R:
# Construct a 3x3 experimental assay matrix
assay_matrix = matrix(
c(0.12, 0.85, 0.33,
0.91, 0.45, 0.15,
0.28, 0.77, 0.94),
nrow = 3, byrow = TRUE,
dimnames = list(c("SampleA", "SampleB", "SampleC"), c("Assay1", "Assay2", "Assay3"))
)
# Identify row and column positions where signal exceeds 0.80
strong_signals = which(assay_matrix >= 0.80, arr.ind = TRUE)
print(strong_signals)
# Output:
# row col
# SampleA 1 2
# SampleB 2 1
# SampleC 3 3
The resulting matrix explicitly identifies that the threshold was exceeded at row 1 column 2, row 2 column 1, and row 3 column 3. Because useNames = TRUE operates by default, the row names of the output matrix inherit the sample identifiers from the original matrix.
Step 5: Combine multiple conditional filters with logical operators
Complex scientific criteria require compounding multiple boolean evaluations. Always use element-wise boolean operators (& for logical AND, | for logical OR, and ! for logical negation) rather than scalar short-circuit operators (&& or ||) inside which():
# Vector of ages and blood pressure readings
age = c(45, 62, 58, 34, 71, 53)
systolic_bp = c(120, 145, 138, 118, 160, 128)
# Find subjects aged 55 or older WITH systolic BP above 140
senior_hypertensive = which(age >= 55 & systolic_bp > 140)
print(senior_hypertensive)
# Output: [1] 2 5
Step 6: Locate extreme values with which.min() and which.max()
When the scientific objective is to identify the location of the single minimum or maximum observation rather than all matching elements, base R provides optimized helper functions: which.min() and which.max(). These functions terminate early and avoid constructing intermediate full-length boolean vectors:
reaction_times = c(412, 385, 510, 298, 345, 460)
# Find index of fastest participant (minimum reaction time)
fastest_idx = which.min(reaction_times)
print(fastest_idx)
# Output: [1] 4
# Retrieve the actual minimum value using the index
min_time = reaction_times[fastest_idx]
print(min_time)
# Output: [1] 298
Step 7: Integrate which() with functional apply routines
In iterative matrix analysis, researchers frequently combine which() with functional mapping routines from the apply family in R to evaluate conditional indices row-by-row or column-by-column across large experimental matrices:
# Locate which assay column achieved maximum response for each sample row
max_col_per_sample = apply(assay_matrix, 1, which.max)
print(max_col_per_sample)
# Output:
# SampleA SampleB SampleC
# 2 1 3
Output and how to read it
Interpreting the output of which() requires understanding its structural returns across three primary dimensions: vector evaluation, multidimensional matrix subscripting, and empty match handling.
When evaluated against a standard one-dimensional vector, which() returns a standard integer vector (storage mode integer). The length of this integer vector exactly equals the number of elements in the input that evaluated to TRUE, which can also be calculated independently as sum(x, na.rm = TRUE). Each integer in the returned vector represents a 1-based numerical index corresponding to the sequential position of the qualifying element. If the original vector possessed an active names attribute and useNames = TRUE was maintained, the output integer vector preserves these character names as vector labels.
When evaluated against a matrix or array with arr.ind = TRUE, which() outputs a two-dimensional integer matrix. The number of rows in this matrix equals the count of TRUE instances, while the number of columns equals the dimensional rank of the original array (for a 2D matrix, exactly 2 columns named row and col). Each row in this returned coordinate matrix acts as a multidimensional subscript. A powerful feature of R is that this coordinate matrix can be passed directly back into matrix bracket notation to extract or overwrite the identified cells simultaneously:
# Extract values directly using the coordinate matrix output
extracted_values = assay_matrix[strong_signals]
print(extracted_values)
# Output: [1] 0.85 0.91 0.94
When zero elements satisfy the supplied logical condition, which() returns an empty integer vector, represented in R as integer(0). If arr.ind = TRUE was specified on a matrix where no elements match, which() returns a 0-row matrix with the appropriate column headers (e.g., a matrix of dimension 0 by 2). Recognizing integer(0) is fundamental to writing robust automated pipelines: integer(0) has a length of 0, meaning mathematical operations or conditional statements that expect a single scalar logical value will fail if this case is not explicitly handled.
The data table below compares base R indexing, matching, and filtering functions across structural attributes, missing value behavior, and output structures.
Troubleshooting
While which() is straightforward to invoke, subtle edge cases involving missing data, empty matches, operator selection, and memory consumption frequently trip up researchers. Below are the primary failure modes and their exact technical resolutions.
1. The empty match trap in control flow statements
A frequent programming error occurs when researchers attempt to test whether a value exists using which() inside if statements in R:
# Flawed implementation
scores = c(72, 85, 91)
if (which(scores > 95)) {
message("High score detected")
}
# Error in if (which(scores > 95)) {: argument is of length zero
Because no score exceeds 95, which(scores > 95) returns integer(0). In R, the if() statement requires a single logical scalar (TRUE or FALSE) of length 1. Supplying a vector of length 0 triggers an immediate runtime error. To resolve this issue, use any() if you merely need to test existence, or wrap the index test with length() > 0:
# Correct implementation using any()
if (any(scores > 95)) {
message("High score detected")
}
# Correct implementation using length()
match_idx = which(scores > 95)
if (length(match_idx) > 0) {
message("Found matches at indices: ", paste(match_idx, collapse = ", "))
}
2. The missing value (NA) discrepancy
One of the most consequential differences between which() and direct vector bracket subsetting is how missing values (NA) are treated. Under direct logical indexing in R, evaluating a condition containing NA yields an NA element in the boolean vector. When passed into vector brackets x[condition], R includes an NA in the extracted output because it cannot determine whether the missing observation met the condition:
# Vector containing missing data
data_vec = c(10, 25, NA, 40, NA, 15)
# Direct logical indexing retains NAs
subset_direct = data_vec[data_vec > 20]
print(subset_direct)
# Output: [1] 25 NA 40 NA
# Subsetting via which() automatically omits NAs
subset_which = data_vec[which(data_vec > 20)]
print(subset_which)
# Output: [1] 25 40
By formal design, which() treats NA values as FALSE, systematically omitting them from the returned integer index vector. While this behavior is often advantageous for cleaning messy survey data, analysts must remain aware of this distinction: if your research methodology requires imputing or explicitly reporting missing values, using which() will silently exclude those records from subsequent calculations.
3. Performance overhead and unnecessary index generation
A common anti-pattern in R data analysis is wrapping every filtering operation in which() unnecessarily. For instance, when subsetting rows in a data frame where missing values are already handled or absent, writing df[which(df$group == "A"), ] forces R to allocate an intermediate integer vector in memory before performing row selection. In large-scale genomics or high-frequency sensor datasets containing millions of rows, direct logical subsetting (df[df$group == "A" & !is.na(df$group), ]) avoids this extra integer allocation, resulting in lower memory churn and faster execution.
4. Accidental matrix flattening without arr.ind
If you evaluate a conditional statement on a matrix without setting arr.ind = TRUE, which() treats the matrix as a flattened, column-major one-dimensional vector:
mat = matrix(1:9, nrow = 3, ncol = 3)
# In column-major order:
# 1 4 7
# 2 5 8
# 3 6 9
# Flawed attempt to find cell coordinates of value 8
flat_idx = which(mat == 8)
print(flat_idx)
# Output: [1] 8 (linear index: column 3, row 2)
# Correct multidimensional coordinates
coord_idx = which(mat == 8, arr.ind = TRUE)
print(coord_idx)
# Output:
# row col
# [1,] 2 3
To avoid confusing linear vector positions with row and column numbers, always verify whether downstream functions expect two-dimensional coordinates or linear memory offsets.
5. Confusing element-wise and scalar boolean operators
Inside which(), passing compound conditions with && (scalar AND) or || (scalar OR) produces silent logical errors. In R, && and || evaluate only the first element of each vector and short-circuit the remaining evaluations. When used within which(), they evaluate the first observation and broadcast that single boolean outcome across the entire vector. Always verify that compound filtering expressions strictly employ the vectorized operators &, |, and !.
Free alternatives
While which() is an essential tool in base R, multiple built-in and open-source alternatives offer distinct advantages depending on whether your workflow prioritizes memory efficiency, non-standard evaluation, readability, or big data processing speed. The table below outlines how which() compares to alternative filtering mechanisms available within the R software ecosystem.
| Tool or Method | Package or Ecosystem | Primary Output Type | NA Handling | Best Research Application |
|---|---|---|---|---|
| which() | Base R (base) | Integer indices or coordinate matrix | Silently omitted (treated as FALSE) | Locating element coordinates, array subscripting, and index-based cross-referencing. |
| Logical Subsetting [] | Base R (base) | Subsetted data vector or data frame | Retained as NA entries in output | High-speed vectorized subsetting when index numbers are not explicitly required. |
| subset() | Base R (base) | Filtered data frame or matrix | Omitted automatically | Interactive exploratory analysis; convenient syntax without repetitive dollar-sign indexing. |
| filter() | Tidyverse (dplyr package) | Tibble or data frame | Omitted automatically | Tidy data manipulation pipelines and readable script workflows across research teams. |
| data.table row indexing | CRAN (data.table) | data.table object | Omitted or configurable | Ultra-high-performance filtering on massive tabular datasets using indexed binary search. |
| match() and %in% | Base R (base) | First match index or boolean mask | Matches NA if configured | Relational key joins, set membership testing, and dictionary lookups across vectors. |
Direct logical indexing via standard brackets (x[condition]) remains the foundational approach in base R. When a researcher does not need to know the specific line numbers where an event occurred, boolean masking operates with minimal computational overhead. However, analysts must explicitly filter out missing data using !is.na(condition) to avoid contaminating downstream data frames with empty NA rows.
The base R subset() function offers clean, readable syntax for interactive data exploration. By leveraging non-standard evaluation, it allows researchers to refer to data frame columns directly without repeatedly prefixing column names with df$. Furthermore, subset() automatically excludes NA conditions, mirroring the missing-data behavior of which(). However, the official R documentation explicitly cautions against using subset() in automated, production-grade scripts or package functions due to the unpredictable scoping characteristics of non-standard evaluation.
For research teams operating within the modern data science ecosystem, the filter() verb from the dplyr package provides an expressive, standardized approach to tabular filtering. Like subset() and which(), filter() automatically drops rows where logical criteria evaluate to FALSE or NA. When integrated into piping pipelines using the native R pipe operator |>, filter() produces transparent data transformation workflows that simplify code auditing and peer review reproducibility.
When working with large administrative registries, electronic health records, or biobank genomic datasets comprising tens of millions of rows, the data.table package offers unmatched indexing performance. By creating keyed indices, data.table executes conditional filtering using fast binary search algorithms rather than scanning entire columns sequentially, reducing lookup times from seconds to microseconds.
Frequently asked questions
What does which() return when no elements match the condition?
When no elements satisfy the supplied logical condition, which() returns an empty integer vector: integer(0). If arr.ind = TRUE was specified on an array or matrix, it returns a 0-row integer matrix with dimension c(0, ncol). Because integer(0) has a length of 0, attempting to evaluate it directly inside a conditional if() statement will throw an error stating that the argument is of length zero. Always verify results using length(which(...)) > 0 or any(...) before passing them into control flow blocks.
How does which() handle missing values (NA) in R?
By official specification, which() treats missing values (NA) as FALSE. Any element in the logical evaluation vector that contains an NA is omitted from the returned integer index vector. This contrasts sharply with standard bracket subsetting (x[condition]), where NA evaluations produce literal NA records in the extracted output. While this makes which() convenient for ignoring missing records, researchers must be careful not to inadvertently drop unobserved data points that require statistical imputation or reporting.
What is the difference between which(x > 5) and x[x > 5]?
The call which(x > 5) outputs the integer index positions (e.g., indices 1, 4, 8) where elements in x are strictly greater than 5. In contrast, x[x > 5] outputs the actual data values stored at those locations. Furthermore, if x contains missing values, x[x > 5] inserts NA entries into the output for each missing observation, whereas x[which(x > 5)] drops those missing entries entirely because which() excludes NA evaluations.
How do you find the row and column coordinates of an element in a matrix?
To obtain two-dimensional coordinates rather than a linear vector index, invoke which() with the argument arr.ind = TRUE (array indices). For example, which(my_matrix == target_value, arr.ind = TRUE) returns an integer matrix where the first column (row) indicates the row number and the second column (col) indicates the column number for every cell matching the target value. If the original matrix has row and column names, these labels are preserved in the output.
Why does using which() inside an if statement cause an error?
The R if() construct requires a single scalar logical condition of length 1 (either TRUE or FALSE). If the condition passed to which() evaluates to FALSE for all observations, which() returns integer(0), which has length 0 and triggers the error: argument is of length zero. Conversely, if multiple elements match, which() returns an integer vector of length greater than 1, triggering a warning in older R versions or an error in recent releases regarding conditions of length greater than one. To test for existence in control flow, use if (any(x > 5)) instead.
How does which.min() differ from which(x == min(x))?
The which.min() function is an optimized base R routine that identifies the index position of the first minimum value in a numeric or logical vector. Unlike which(x == min(x)), which.min() does not evaluate the entire vector twice or construct intermediate boolean vectors. Furthermore, if multiple elements share the identical minimum value, which.min() returns only the index of the first occurrence, whereas which(x == min(x)) returns the indices of all tied minimums. Finally, which.min() automatically discards NA and NaN values without requiring an explicit na.rm = TRUE argument.
Can which() be used on data frame columns and character strings?
Yes. The which() function operates on any logical vector resulting from evaluations on data frame columns or character vectors. For example, to find the row numbers in a patient cohort where the diagnosis column equals “Type 2 Diabetes”, write which(patients$diagnosis == "Type 2 Diabetes"). Similarly, you can locate specific column positions by evaluating against column names: which(names(df) == "target_variable").
Sources
- R Core Team. (2026). which: Which indices are TRUE? R Base Package Reference Manual. Comprehensive R Archive Network (CRAN). Accessed 2026-11-16. https://stat.ethz.ch/R-manual/R-devel/library/base/html/which.html
- R Core Team. (2026). which.min: Where is the Min() or Max() or first TRUE or FALSE? R Base Package Reference Manual. Comprehensive R Archive Network (CRAN). Accessed 2026-11-16. https://stat.ethz.ch/R-manual/R-devel/library/base/html/which.min.html
- R Core Team. (2026). An Introduction to R: A Programming Environment for Data Analysis and Graphics. CRAN Documentation. Accessed 2026-11-16. https://cran.r-project.org/doc/manuals/r-release/R-intro.html
- R Core Team. (2026). R Language Definition. CRAN Documentation. Accessed 2026-11-16. https://cran.r-project.org/doc/manuals/r-release/R-lang.html
- R Core Team. (2026). subset: Subsetting Vectors, Matrices and Data Frames. R Base Package Reference Manual. Comprehensive R Archive Network (CRAN). Accessed 2026-11-16. https://stat.ethz.ch/R-manual/R-devel/library/base/html/subset.html
- R Core Team. (2026). match: Value Matching. R Base Package Reference Manual. Comprehensive R Archive Network (CRAN). Accessed 2026-11-16. https://stat.ethz.ch/R-manual/R-devel/library/base/html/match.html
Data: Comparison of Base R Indexing and Condition Identification Functions
A comparative analysis of base R indexing, matching, and filtering functions, detailing input requirements, output data structures, missing value behavior, multidimensional array support, and computational paradigms compiled from the official R Core Team base manual pages.
| Function Name | Primary Input Type | Output Data Structure | Missing Value (NA) Handling | Empty Match Output | Multidimensional Support | Execution Paradigm |
|---|---|---|---|---|---|---|
| which() | Logical vector or array | Integer vector or coordinate matrix | Omitted (treated as FALSE) | integer(0) or 0-row matrix | Yes (arr.ind = TRUE) | Eager evaluation / positional extraction |
| which.min() | Numeric or logical vector | Single integer scalar | Omitted (discarded automatically) | integer(0) | No (flattens dimensions) | Early termination at first minimum |
| which.max() | Numeric or logical vector | Single integer scalar | Omitted (discarded automatically) | integer(0) | No (flattens dimensions) | Early termination at first maximum |
| match() | Vector of lookup keys and table | Integer vector of positions | Matches NA if incomparables = FALSE | nomatch value (default NA_integer_) | No (1D vectors only) | Hash table lookup on first match |
| %in% | Vector of candidate values and set | Logical vector (TRUE/FALSE) | Evaluates NA %in% table as boolean | logical(0) | No (coerced to 1D vector) | Vectorized wrapper around match() > 0L |
| subset() | Data frame, matrix, or vector | Filtered object of same class | Omitted (drops NA rows like which) | 0-row data frame or empty vector | Yes (2D row and column selection) | Non-standard evaluation expression |
Sources
- R Documentation: which - Which indices are TRUE? (accessed 2026-11-16)
- R Documentation: which.min - Where is the Min() or Max() or first TRUE or FALSE? (accessed 2026-11-16)
- R Documentation: match - Value Matching (accessed 2026-11-16)
- R Documentation: subset - Subsetting Vectors, Matrices and Data Frames (accessed 2026-11-16)
- The R Project for Statistical Computing: An Introduction to R (accessed 2026-11-16)
Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.







