Using haven to label data for STATA: Error: If any elements of `.data` are named, all must be named

Hi There,

I'm using haven to label my variables for STATA data exports. For more information about the method I'm using, follow this link: Haven seems to recode/change variable values when exporting labeled data to SPSS and Stata. Here is the example code:

library(haven)

lookup <- lookup <- c(
  "Never [0]"                  = 0,
  "Monthly or less [1]"        = 1,
  "2 to 4 times a month [2]"   = 2,
  "2 to 3 times a week [3]"    = 3,
  "4 or more times a week [4]" = 4
)

audit$a_audit_1_1 =  factor(
  audit$a_audit_1_1,
  levels = lookup,
  labels = names(lookup)
)

# do other tasks in R...
audit$a_audit_1_1 <- labelled(
  x      = lookup[as.character(audit$a_audit_1_1)],
  labels = lookup
)
write_dta(audit, ...)

Since yesterday, I'm getting the following error for all my variables:

> library(haven)
> df$group <-
+         labelled(x  =  group_lookup[as.character(df$group)],
+                  labels = group_lookup, label = "Study Group")
Error: If any elements of `.data` are named, all must be named
> 

None of my variables are labeled in the STATA export.

I'm assuming that the error might be related to this: More descriptive error message needed if column names are NA .

I have more than a thousand variables and I can't figure out why this problem recently started or which variable is causing the problem.

Here are a few additional things I've tried to identify missing column names:

> names(df)[names(df) == ""]
character(0)
> 
> names(df)[is.na(names(df))]
character(0)
>
> traceback()
6: stop("If any elements of `.data` are named, all must be named", 
       call. = FALSE)
5: validate_names(.data)
4: new_vctr(x, labels = labels, label = label, ..., class = c(class, 
       "haven_labelled"), inherit_base_type = TRUE)
3: new_labelled(x, labels = labels, label = label)
2: validate_labelled(new_labelled(x, labels = labels, label = label))
1: labelled(x = group_lookup[as.character(df$group)], labels = group_lookup, 
       label = "Study Group")
>

I would appreciate any ideas on how to troubleshoot this further.

Thank you.

André

I've also logged an issue on the Haven GitHub repository and will update this post with any updates.

It seems to be an issue in haven version 2.3.1.

This resolved the problem:

remove.packages("haven")
Removing package from ‘C:/Users/andre/Documents/R/win-library/4.0’
(as ‘lib’ is unspecified)
library(devtools)
Loading required package: usethis
install_version("haven", version = "2.2.0", repos = "http://cran.us.r-project.org")

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.