In R, some packages (e.g. haven
) insert a label
attributes to variables (e.g. haven
), which explains the substantive name of the variable. For example, gdppc
may have the label GDP per capita
.
This is extremely useful, especially when importing data from Stata. However, I still struggle to know how to use this in my workflow.
How to quickly browse the variable and the variable label? Right now I have to do attributes(df$var)
, but this is hardly convenient to get a glimpse (a la names(df)
)
How to use these labels in plots? Again, I can use attr(df$var, "label")
to access the string label. However, it seems cumbersome.
Is there any official way to use these labels in a workflow? I can certainly write a custom function that wraps around the attr
, but it may break in the future when packages implement the label
attribute differently. Thus, ideally I'd want an official way supported by haven
(or other major packages).
If you don't remember name of the label attached to a variable, you can find it with the help of the describe or the codebook command (just insert the variable name after the respective command). As of Stata version 12, value labels are also shown in the "Variables" section of the Properties window.
label define defines a list of up to 65,536 (1,000 for Small Stata) associations of integers and text called value labels. Value labels are attached to variables by label values. label values attaches a value label to varlist. If . is specified instead of lblname, any existing value label is detached from that varlist.
How do I open a Stata file in R. To open a Stata file in R you can use the read_dta() function from the library called haven.
A solution with purrr package from tidyverse:
df %>% map_chr(~attributes(.)$label)
Using sapply in a simple function to return a variable list as in Stata's Variable Window:
library(dplyr)
makeVlist <- function(dta) {
labels <- sapply(dta, function(x) attr(x, "label"))
tibble(name = names(labels),
label = labels)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With