strengejacke / sjlabelled

Working with Labelled Data in R

Home Page:https://strengejacke.github.io/sjlabelled

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

as_labelled missing additional classes used by haven

detroyejr opened this issue · comments

Issue

Rstudio prints labelled data nicely in a format that's easier to read. Using as_labelled to convert factors to labelled data messes with this formatting.

packageVersion("haven")
#> [1] '2.3.1'
packageVersion("sjlabelled")
#> [1] '1.1.7'


# SAV data read with the latest version of haven.
x <- structure(
  c(2, 1, 2, 2, 1, 1), 
  label = "What is your gender?", 
  format.spss = "F1.0", 
  display_width = 1L, 
  labels = c(Male = 1, Female = 2), 
  class = c("haven_labelled", "vctrs_vctr", "double")
)

RStudio prints labelled data differently than a regular r console.

# <labelled<double>[6]>: What is your gender?
#  [1] 2 1 2 2 1 1
#
# Labels:
#  value  label
# 1   Male
# 2 Female

The print formatting is lost when using as_labelled.

y <- structure(
  c(1L, 1L, 1L, 1L, 1L, 1L), 
  .Label = c("setosa", "versicolor", "virginica"), 
  class = "factor"
)
y <- sjlabelled::as_labelled(y)

Prints like it does in a regular R console.

# [1] 1 1 1 1 1 1
# attr(,"labels")
# setosa versicolor  virginica 
# 1          2          3 
# attr(,"class")
# [1] "haven_labelled"

Solution

as_labelled should add two additional classes.

class(sjlabelled::as_labelled(y))
#> [1] "haven_labelled"
class(x)
#> [1] "haven_labelled" "vctrs_vctr"     "double"

class(y) <- c("haven_labelled", "vctrs_vctr", "double")

# Displays correctly in the Rstudio Terminal.
# <labelled<double>[6]>
#   [1] 1 1 1 1 1 1

# Labels:
#   value      label
# 1     setosa
# 2 versicolor
# 3  virginica

Not a huge issue, but a small cosmetic thing that’s easily fixed. I haven't noticed any problems with the latest version of haven so I assume this wouldn't break anything. I’ll submit a PR and you can decide what to do about it.

Thanks!

Created on 2020-10-01 by the reprex package (v0.3.0)