Unfortunately, pivot_longer by itself doesn't directly expose or extract column attributes like label. pivot_longer is designed to reshape data, not to inspect and integrate metadata associated with columns. Therefore, you can't do this purely with pivot_longer.
You'll need a pre-processing or post-processing step around pivot_longer to achieve your goal. Here are a few approaches, demonstrating how to add the column labels as a new column:
1. Pre-processing with mutate and across:
This is often the most direct and readable way, especially if you're working with a dplyr workflow. Before pivoting, create the column you want with the label as the value.
library(dplyr)
library(tidyr)
# Example data with labels
df <- data.frame(
col1 = 1:3,
col2 = 4:6
)
attr(df$col1, "label") <- "Column One Label"
attr(df$col2, "label") <- "Column Two Label"
df %>%
mutate(across(everything(),
~ {
lab <- attr(., "label")
if (is.null(lab)) lab <- "" # Handle columns without labels
attr(., "label") <- lab # Restore the attribute, maybe not needed
. # Return the original column value
}
)) %>% # Make sure attributes are restored
pivot_longer(everything(), names_to = "name", values_to = "value") %>%
mutate(label = case_when(
name == "col1" ~ attr(df$col1, "label"),
name == "col2" ~ attr(df$col2, "label")
))
# Equivalent using purrr::map_chr and more flexible
df %>%
pivot_longer(everything(), names_to = "name", values_to = "value") %>%
mutate(label = purrr::map_chr(name, ~attr(df[[.]], "label") %||% "")) # Use %||% for easy default
Key improvements:
- Handles missing labels: The
if (is.null(lab)) lab <- "" (or %||% "") part is crucial. If a column doesn't have a label attribute, this prevents errors and assigns a sensible default (here, an empty string).
- Clarity: Using
across makes it clear that you're applying a transformation to every column, restoring attributes (if desired)
2. Post-processing with left_join (if you can predefine the labels):
If you have a known mapping between column names and labels, you can create a lookup table and join it after pivoting. This might be useful if the labels are stored elsewhere or derived from some other source.
library(dplyr)
library(tidyr)
# Example data with labels (as before)
df <- data.frame(
col1 = 1:3,
col2 = 4:6
)
attr(df$col1, "label") <- "Column One Label"
attr(df$col2, "label") <- "Column Two Label"
# Create a lookup table
label_table <- tibble(
name = c("col1", "col2"),
label = c(attr(df$col1, "label"), attr(df$col2, "label"))
)
df %>%
pivot_longer(everything(), names_to = "name", values_to = "value") %>%
left_join(label_table, by = "name")
This approach is more structured when you have multiple labels to add, rather than just the column label.
3. Using a custom function (more complex but potentially reusable):
You could wrap the whole process into a custom function that extracts labels and then pivots. This offers reusability but adds complexity.
library(dplyr)
library(tidyr)
# Example data with labels (as before)
df <- data.frame(
col1 = 1:3,
col2 = 4:6
)
attr(df$col1, "label") <- "Column One Label"
attr(df$col2, "label") <- "Column Two Label"
pivot_longer_with_labels <- function(data) {
# Extract labels
labels <- sapply(names(data), function(col_name) {
attr(data[[col_name]], "label") %||% "" # Use %||% for a default empty string
})
# Pivot longer
data_long <- data %>%
pivot_longer(everything(), names_to = "name", values_to = "value")
# Add labels
data_long %>%
mutate(label = labels[name])
}
result <- pivot_longer_with_labels(df)
print(result)
Key points about this function:
sapply is used to efficiently extract labels for all columns, handling the NULL case with %||% "".
- The
labels[name] indexing is key to matching the correct label to the pivoted column name.
Choosing the right approach:
- Pre-processing (option 1): Best for simple cases, clear and readable within a pipe. Handles missing labels well.
- Post-processing (option 2): Suitable when labels are defined separately from the dataframe itself or derived from another source. Useful when you need to join on multiple sets of metadata beyond just the column label.
- Custom function (option 3): Good for reusability if you need this functionality in multiple places, but it's the most complex.
The first pre-processing example with mutate and across is generally the most recommended approach for its clarity and flexibility. Remember to adapt the code to handle the potential absence of a "label" attribute. The %||% operator from rlang provides a clean way to provide a default value when the attribute is NULL. I've incorporated that in the suggested solutions.