Get index of a name in a vector, row, or column
stm_get_index.Rd
stm_get_index()
searches for a specified name in a given vector,
row, or column of a data structure (vector, matrix, or data frame), and
returns its index. It supports stopping the search if the name is not found.
Arguments
- dat
A vector, matrix, or data frame in which to search for the specified name. It must be iterable and contain character elements.
- name_to_find
A string representing the name to search for in
data
.- is_columns
Optional. A logical value indicating whether to search in columns (
TRUE
) or rows (FALSE
) of a matrix or data frame. Defaults toTRUE
.- is_stop
Optional. A logical value indicating whether to stop the function and raise an error if the name is not found. Defaults to
FALSE
.
Value
An integer index if the name is found, otherwise NULL
if
is_stop
is FALSE
, or an error if is_stop
is
TRUE
.
Details
The function checks if the provided data
is a vector, matrix, or
data frame, and performs a search for name_to_find
in the specified
row or column. If the name is not found and is_stop
is TRUE
,
the function stops and raises an error with a message containing the
search target and data structure. If is_stop
is FALSE
, the
function returns NULL
.
Examples
v <- c("A", "B", "C")
print(v)
#> [1] "A" "B" "C"
stm_get_index(v, name_to_find = "B")
#> [1] 2
df <- data.frame(A = 1:3, B = 4:6, C = 7:9)
print(df)
#> A B C
#> 1 1 4 7
#> 2 2 5 8
#> 3 3 6 9
stm_get_index(df, name_to_find = "C")
#> [1] 3
A <- matrix(1:6, nrow = 2, byrow = TRUE,
dimnames = list(c("X", "Y"), c("A", "B", "C"))
)
print(A)
#> A B C
#> X 1 2 3
#> Y 4 5 6
stm_get_index(A, name_to_find = "A")
#> [1] 1
stm_get_index(A, name_to_find = "Y", is_columns = FALSE)
#> [1] 2
stm_get_index(A, name_to_find = "Z", is_columns = FALSE)
#> NULL