rdataframevectorlabel

How to label colnames of a dataframe directly with a vector


I have a dataframe with 300 columns. I would like to label the columns with a vector (consisting of 300 entries). I try to use the labelled package. But I don't want to assign each variable to a label one by one -> id= "Identity", age = "Age"....etc. I would like to assign the label names from a vector directly to the columns -> c("Identity", "Age", ...

Example:

library(tidyverse)
library(labelled)

#dataframe
df <- data.frame(matrix(0, ncol = 300, nrow = 2))
#vector of labels for columns
label_colname <- sprintf("label_colname[%d]",seq(1:300))

df %>% set_variable_labels(label = label_colname)

error in set_variable_labels(., label = label_colname) : some variables not found in .data


Solution

  • Since label is just stored as an attribute you can also do this directly in base R:

    for (i in seq_along(df)) {
      attr(df[[i]], "label") <- label_colname[i]
    }
    

    enter image description here