使用 Haven 导入 Stata 数据后访问变量标签的便捷方式 [英] Convenient way to access variables label after importing Stata data with haven

查看:14
本文介绍了使用 Haven 导入 Stata 数据后访问变量标签的便捷方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

  1. 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))

  2. 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).

解决方案

A solution with purrr package from tidyverse:

df %>% map_chr(~attributes(.)$label)

这篇关于使用 Haven 导入 Stata 数据后访问变量标签的便捷方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆