When To Use Which in R?

Do you need to determine which component of a vector, data frame, or matrix satisfies a given set of criteria? then you’re in the right place.

which(x, arr.ind = FALSE)
x: Any logical test vector.

When working with matrices (multiple dimension arrays), the optional argument arr.ind is used to specify that you require the array indices (both x and y data points, for example, vs a single index for one-dimensional arrays).

When scanning a data structure in R, you may use the function which to find the items that satisfy a given criterion.

The indexes of the matching elements in the data object are returned by the which function.

Which() r examples

Let’s get directly to some examples of the which function r.

Examples of which function in the R language

list <-c('Hello','welcome','to','finnstats.com','You','can','find','more','article','here')
which(list=='finnstats.com')
[1] 4

finnstats.com is indeed at position 4 in the list

which(list=='datascience')
integer(0)

It appears that we didn’t satisfy them because the missing values are zeros.

which R Data Frame Function

R data frames can be used with the which function as well. In the example that follows, we’ll find the indexes of a portion of the ChickWeight data frame that satisfy a specific requirement (Time = day 20).

The evolution of a flock of chickens fed various diets over time is shown in this built-in data set for R.

which function in an r data frame

which(ChickWeight$Time==20)
[1]  11  23  35  47  59  71  83  95 106 118 130 142 154 166 193 207 219 231 243 255 267 279 291 303 315 327 
39 351 363 375 387 399 411 423 435 447 459 471 483 495 517 529 541 553 565 577

As we can see, when the time was equal to 20, the which function retrieved the indices for all of the data points.

Additional Applications

The function need not only be looking for equality; it can also be used with any other logical test. The function can be applied to multidimensional matrices, as was already indicated.

What Does This Mean for Which in R?

It is actually a very helpful feature of the R toolkit, particularly if you’re writing programs to clean data and apply statistical methods.

This method captures the process of inspecting a current data structure and flagging the elements that could need further processing.

It may also be applied before a filtering procedure. Use which to identify the observations in a data frame that should be analyzed as part of the whole or separately, return them as a vector of values, and handle them as necessary.

In terms of functional programming, this IS the fundamental underlying operation for “filter” (returning pointers vs. creating an array).

Have you found this article to be interesting? We’d be glad if you could forward it to a friend or share it on Twitter or Linked In to help it spread.

You may also like...

Leave a Reply

Your email address will not be published.