haven icon indicating copy to clipboard operation
haven copied to clipboard

Unable to write tagged NA in SAS format

Open lz100 opened this issue 3 months ago • 0 comments

When some values are tagged NA with labels, write_xpt throws errors

library(dplyr)

data_orig <- tibble(
  var =  c("1", "2", "2", "2", "3", "999", "1", "3", "777", NA),
)

data_labelled_stata_sas <- data_orig |> 
  mutate(
    var = case_when(
      var == 999 ~ haven::tagged_na("d"),
      var == 777 ~ haven::tagged_na("r"),
      .default = as.double(var)
    ) |>
      labelled::set_value_labels(
        c(
          yes   = 1,
          maybe = 2,
          no    = 3,
          "don't know" = haven::tagged_na("d"),
          "refused"    = haven::tagged_na("r")
        )
      ) |> 
      labelled::set_variable_labels(
        "var" = "Do you like ice cream?"
      )
  )

haven::write_xpt(data_labelled_stata_sas, "data_labelled_sas.xpt")
#> Error: Failed to insert value [6, 1]: A provided tag value was outside the range of allowed values in the 
#> specified file format.

Is there a way to make it work?

lz100 avatar May 17 '24 01:05 lz100