如何在R中提取SAS数据的Length、Type属性至表格?
提取SAS数据的变量长度与类型属性
针对你用read.sas7bdat导入的df对象,可通过提取变量的附加sas属性来获取Length(SAS定义的变量长度)和Type(变量类型),以下是完整的实现代码:
library(tibble) library(purrr) var_metadata <- tibble( Variable = names(df), Labels = map_chr(df, attr_getter("label"), .default = NA_character_), Length = map_chr(df, ~ attr(.x, "sas")$length, .default = NA_character_), Type = map_chr(df, ~ { # 优先提取SAS原生类型,无则返回R中的变量类型 sas_type <- attr(.x, "sas")$type if (!is.null(sas_type)) sas_type else typeof(.x) }) )
代码说明
- Length列:
read.sas7bdat会为每个变量绑定一个sas属性列表,其中length字段对应SAS数据集中定义的变量长度,用map_chr遍历提取,.default参数确保遇到无该属性的变量时填充NA。 - Type列:优先提取
sas属性中的type(对应SAS的字符型character、数值型numeric等原生类型),如果该属性不存在,则返回变量在R中的类型(如double、character)。
内容的提问来源于stack exchange,提问作者Stataq
相关产品推荐
相关产品推荐

