tommaso crosta
tommaso crosta

Reputation: 15

Creating a codebook in R that considers non-labelled variables

I found a useful and simple function which creates a codebook for .dta datasets in R, the code is the following:

codebook <- map_df(dt, function(x) attributes(x)$label) %>% 
  gather(key = Code, value = Label) %>% 
  mutate(Type = map_chr(dt, typeof),
         Mean = map_dbl(dt, mean, na.rm = T),
         Prop_miss = map_dbl(dt, function(x) mean(is.na(x))))

The function works just fine, unless there are variables in the dataset that are unlabaled, in that case it doesn't. I would like to modify it so that it also reports variables with no labels as "UNLABELED" along with the rest of the information. I tried something like this:

if (map_df(dt, function(x) attributes(x)$label) == NULL) {
   attr(function(x) dt$(x), "label") <- "NO LABEL"
}

But it doesn't work (I am not really skilled with coding on R). Thanks in advance for the help.

Upvotes: 1

Views: 154

Answers (1)

akrun
akrun

Reputation: 887711

The `if/else condition would be inside

library(purrr)
map_dfr(dt, ~ {
          if(is.null(attributes(.x)$label)) {
                attr(.x, "label") <- "NO LABEL"
         }
         attributes(.x)$label})

Upvotes: 2

Related Questions