【问题标题】:How to work with labelled data from SPSS in R如何在 R 中处理来自 SPSS 的标记数据
【发布时间】:2017-11-23 10:58:07
【问题描述】:

这是我发现的一个解决方案,可以在 R 中处理来自 SPSS 的标记数据。

我正在处理 SPSS 中提供的一项调查,我从 foreign 移动到 haven

我阅读了Convenient way to access variables label after importing Stata data with haven,但找不到将我标记的变量表示为因子的方法。

我尝试的是使用purrr 包提取attributes,然后将一些变量转换为因子。没有成功!

如何在 R 中处理来自 SPSS 的标记数据

1:读取数据

library(dplyr)
library(haven)
library(purrr)
library(sjlabelled)

url = "http://users.dcc.uchile.cl/~mvargas/auxiliares_cc5208/nesi_individuals_with_grants_2015_spss.zip"
zip = paste0(getwd(),"/nesi_individuals_with_grants_2015_spss.zip")
sav = paste0(getwd(),"/nesi_individuals_with_grants_2015.sav")

download.file(url, zip, method="curl")

system(paste0("7z e ",zip," -oc:",getwd()))

nesi_individuals_with_grants = tbl_df(read_sav(sav))

# as expected the variables have no levels
# B14 is a variable that refers to where do people work (e.g. 1= startup, 2= bank, 3 = hospital, etc)
levels(nesi_individuals_with_grants$B14)

2:创建一个表格来获取数字(标签)的含义:

classifications_all = tbl_df(nesi_individuals_with_grants) %>% 
    select(OCUP_REF,SEXO,CISE,CINE,B1,B14,C1) %>% 
    rename(occupation_id = OCUP_REF, sex_id = SEXO, icse_id = CISE, isced_id = CINE,
           isco_id = B1, journey_id = C1)

  occupation = classifications_all %>% 
    select(occupation_id) %>% 
    mutate(occupation = get_label(occupation_id)) %>% 
    distinct()

返回

# A tibble: 3 x 2
  occupation_id                                           occupation
      <dbl+lbl>                                                <chr>
1             1 Binario Ocupados de Referencia Tabulados de Personas
2           NaN Binario Ocupados de Referencia Tabulados de Personas
3             0 Binario Ocupados de Referencia Tabulados de Personas

哪个是变量标签,那我试试

  occupation = classifications_all %>% 
    select(occupation_id) %>% 
    distinct() %>% 
    filter(!is.nan(occupation_id)) %>% 
    mutate(occupation = get_labels(occupation_id))

有效!

> occupation
# A tibble: 2 x 2
  occupation_id                                      occupation
      <dbl+lbl>                                           <chr>
1             1 Ocupados con menos de 1 mes en el empleo actual
2             0   Ocupados con más de 1 mes en el empleo actual

【问题讨论】:

  • 缺少库调用? :Error in mutate_impl(.data, dots) : could not find function "get_label" 或许来自 {sjmisc} 的 get_label
  • sjmisc 说“使用 sjlabelledbc 这将被弃用”

标签: r tidyverse purrr r-haven


【解决方案1】:

您想将值标签设置为因子水平吗?然后你可以试试sjlabelled::as_label()sjmisc::to_label()(两者都是一样的,只是我没有从sjmisc 中完全删除to_label,而是为了向后兼容而保留它)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-22
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    • 2014-05-27
    • 1970-01-01
    • 2010-10-05
    • 1970-01-01
    相关资源
    最近更新 更多