The which() serve as in R returns the location of components in a logical vector which are TRUE.
This educational supplies a number of examples of the way to importance this serve as in observe.
Instance 1: In finding Components in a Vector
Refer to code displays the way to to find the location of all components in a vector which are equivalent to five:
#assemble knowledge knowledge <- c(1, 2, 2, 3, 4, 4, 4, 5, 5, 12) #to find the location of all components equivalent to five which(knowledge == 5) [1] 8 9
We will be able to see that the weather in positions 8 and 9 within the vector are equivalent to the price 5.
We will be able to additionally to find the location of all components in a vector which are no longer equivalent to five:
#to find the location of all components no longer equivalent to five which(knowledge != 5) [1] 1 2 3 4 5 6 7 10
We will be able to additionally to find which components are between two values or outdoor of 2 values:
#to find the location of all components with values between 2 and four which(knowledge >= 2 & knowledge <= 4) [1] 2 3 4 5 6 7 #to find the location of all components with values outdoor of two and four which(knowledge < 2 | knowledge > 4) [1] 1 8 9 10
Instance 2: Rely Occurrences in a Vector
Refer to code displays the way to importance the field() serve as to seek out the selection of components in a vector which are more than some worth:
#assemble knowledge knowledge <- c(1, 2, 2, 3, 4, 4, 4, 5, 5, 12) #to find selection of components more than 4 field(which(knowledge > 4)) [1] 3
We will be able to see that there are 3 components on this vector with values more than 4.
Instance 3: In finding Rows in a Knowledge Body
Refer to code displays how to go back the row in an information body that incorporates the max or min worth in a undeniable column:
#assemble knowledge body
df <- knowledge.body(x = c(1, 2, 2, 3, 4, 5),
y = c(7, 7, 8, 9, 9, 9),
z = c('A', 'B', 'C', 'D', 'E', 'F'))
#view knowledge body
df
x y z
1 1 7 A
2 2 7 B
3 2 8 C
4 3 9 D
5 4 9 E
6 5 9 F
#go back row that incorporates the max worth in column x
df[which.max(df$x), ]
x y z
6 5 9 F
#go back row that incorporates the min worth in column x
df[which.min(df$x), ]
x y z
1 1 7 A
Instance 4: Subset through Rows in a Knowledge Body
Refer to code displays the way to subset an information body through rows that meet a undeniable standards:
#assemble knowledge body
df <- knowledge.body(x = c(1, 2, 2, 3, 4, 5),
y = c(7, 7, 8, 9, 9, 9),
z = c('A', 'B', 'C', 'D', 'E', 'F'))
#view knowledge body
df
x y z
1 1 7 A
2 2 7 B
3 2 8 C
4 3 9 D
5 4 9 E
6 5 9 F
#go back subset of information body the place values in column y are more than 8
df[which(df$y > 8), ]
x y z
4 3 9 D
5 4 9 E
6 5 9 F
In finding extra R tutorials in this web page.