diff --git a/NEWS.md b/NEWS.md index 7f19402e7..a1137ff24 100644 --- a/NEWS.md +++ b/NEWS.md @@ -41,6 +41,10 @@ BUG FIXES * Fixed issues in `data_write()` when writing labelled data into SPSS format and vectors were of different type as value labels. +* Fixed issues in `data_write()` when writing labelled data into SPSS format + for character vectors with missing value labels, but existing variable + labels. + * Fixed issue in `recode_into()` with probably wrong case number printed in the warning when several recode patterns match to one case. diff --git a/R/data_write.R b/R/data_write.R index b8d710d2e..324b71168 100644 --- a/R/data_write.R +++ b/R/data_write.R @@ -142,9 +142,13 @@ data_write <- function(data, # character requires special preparation to save value labels # haven:::vec_cast_named requires "x" and "labels" to be of same type if (is.character(i)) { + # only prepare value labels when these are not NULL + if (!is.null(value_labels)) { + value_labels <- stats::setNames(as.character(value_labels), names(value_labels)) + } haven::labelled( x = i, - labels = stats::setNames(as.character(value_labels), names(value_labels)), + labels = value_labels, label = variable_label ) } else { diff --git a/tests/testthat/test-data_write.R b/tests/testthat/test-data_write.R index a51931bd7..861f67b46 100644 --- a/tests/testthat/test-data_write.R +++ b/tests/testthat/test-data_write.R @@ -132,3 +132,23 @@ test_that("data_write, no file extension", { expect_error(data_write(d, "mytestfile")) expect_error(data_write(d, NULL)) }) + + +# writing character vector works for missing value labels ------------------ + +tmp <- tempfile(fileext = ".sav") +on.exit(unlink(tmp)) + +test_that("data_write, existing variable label but missing value labels", { + d <- data.frame( + a = letters[1:3], + stringsAsFactors = FALSE + ) + d$a <- assign_labels(d$a, variable = "First") + # expect message, but no error + expect_message(data_write(d, tmp), regex = "Preparing") + + # check if data is really the same + d2 <- data_read(tmp) + expect_identical(d2, d) +})