| get_colnames | R Documentation |
This helper function returns column names based on either column
indices (numeric) or column names (character). It works consistently
across data.frame, tibble, and data.table objects.
get_colnames(data, cols, preserve_duplicates = FALSE, preserve_NULL = FALSE)
data |
A data frame, tibble, or data.table. |
cols |
Column selection, either as numeric indices, character names,
or |
preserve_duplicates |
Logical, default |
preserve_NULL |
Logical, default |
By default, cols = NULL returns character(0), matching the
behavior of names(data[1, NULL, drop = FALSE]).
If preserve_NULL = TRUE, the function instead returns NULL.
A character vector of column names, or NULL if cols = NULL
and preserve_NULL = TRUE.
This function is written and documented by ChatGPT after some discussion.
df <- data.frame(a = 1, b = 2, c = 3)
# NULL input handling
get_colnames(df, NULL)
get_colnames(df, NULL, preserve_NULL = TRUE)
# Numeric input
get_colnames(df, c(2, 2, 1))
get_colnames(df, c(2, 2, 1), preserve_duplicates = TRUE)
# Character input
get_colnames(df, c("c", "a", "c"))
get_colnames(df, c("c", "a", "c"), preserve_duplicates = TRUE)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.