Skip to content

allow mutate() to allow combination of labelled and double classes  #5424

Closed
@bhaney22

Description

I would like the dplyr::mutate() command to allow an input variable with combination of "labelled", "haven_labelled", and "double" classes.


My workflow:

  1. Use haven::read_sav() to read in an SPSS file, from the General Social Survey for example
  2. Use the expss::mis_val() to recode var2 to set some categories as NA and remove labels associated with those categories
  3. Use dplyr::mutate(newvar2 = case_when(var2 == 1 ~ 1, var2 == 2 ~ 0)) to create a new variable

EDIT: For clarity so that later comments will make sense, I added the "vctr_vctrs" class to the list of classes in the following statement so that it was complete.

Problem: Step 2. above causes var2 to have this combination of classes: "labelled" "haven_labelled" "vctrs_vctr" "double". This causes dplyr::mutate() to throw the following error when I try to do Step 3.

Error: Problem with mutate() input newvar2.
x Can't combine ..1 <labelled> and ..2 .
ℹ Input newvar2 is case_when(var2 == 1 ~ 1, var2 == 2 ~ 0).

I would like dplyr::mutate() to allow variables with this combination of classes ("labelled" "haven_labelled" "double") as input variables.

NOTE: dplyr::mutate() currently allows an input variable to have a combination of: "haven_labelled" "double"

Below is a minimum working example.

library(haven)
library(expss)
library(dplyr)

var1 <- haven::labelled(c(0, 1, 9, 0, 0),c(`No` = 0, `Yes` = 1, `DK` = 9))
var2 <- haven::labelled(c(0, 1, 2, 3, 1), c(`DK` = 0, `first` = 1, `second` = 2, `third` = 3))
mytest <- tibble(var1,var2)

# Classes before Step 2.
str(attributes(mytest$var1))
str(attributes(mytest$var2))

mytest$var1   <- expss::mis_val(mytest$var1, c(9))
mytest$var2   <- expss::mis_val(mytest$var2, c(0), with_labels = TRUE)

# Classes after Step 2.
str(attributes(mytest$var1))
str(attributes(mytest$var2))

# dplyr::mutate() works with input variable with combination of "haven_labelled" and "double" classes
mytest <- mytest %>%
  mutate(newvar1 = case_when(var1 == 1 ~ 1, var1 ==0 ~ 2)) 

# dplyr::mutate() does not work with combination of "labelled"  "haven_labelled" and "double" classes 

mytest <- mytest %>%
  mutate(newvar2 = case_when(var2 == 1 ~ 1, var2 == 2  ~ 0)) 

# Running the above command should produce the error commented below that I would like fixed.
#   Error: Problem with `mutate()` input `newvar2`.
#   x Can't combine `..1` <labelled<double>> and `..2` <double>.
#   ℹ Input `newvar2` is `case_when(var2 == 1 ~ 1, var2 == 2 ~ 0)`.

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions