Search code examples
rdataframetibble

Adding descriptive text to column names


I recently loaded in some data from a world bank API and when I viewed the dataframe with tibble's view() function, I noticed some nice descriptive metadata text just below the column name, like in the image below

screenshot of the panel

I would like to be able to reproduce this effect in the future, attributes(mtcars)$subheaders <- c("where","are","my","subheaders") did not work for me and I appear to lack the proper technical vocabulary to be able to search for the solution.


Solution

  • You can put all kinds of information in the attributes. Some packages add labels and extra information to factor vectors for instance.

    df <- data.frame(a = 10)
    attr(df$a, "subheader") <- "description of a"
     
    >attr(df$a, "subheader")
    [1] "description of a"
    > 
    > str(df)
    'data.frame':   1 obs. of  1 variable:
     $ a: num 10
      ..- attr(*, "subheader")= chr "description of a"
    

    and you can add a function to get the subheader

    subheader <- function(vec) {
      attr(vec, "subheader")
    }
      
    subheader(df$a)
    

    EDIT

    To have the description show up in View() you can add label as the name of the attribute.

    df <- data.frame(a = 10)
    attr(df$a, "label") <- "description of a"