Search code examples
rstatar-haven

Writing failure: A provided name contains an illegal character. Error while saving R data into Stata format


I am using haven package to write the R dataset into Stata format.

This is the error I am getting.

write_dta(road_panel, "road_panel.dta", version = 14, label = attr(data,"label"))

Error in write_dta_(data, normalizePath(path, mustWork = FALSE), version = stata_file_format(version), : Writing failure: A provided name contains an illegal character.

I also tried a slightly different code but its the same.

`write_dta(road_panel, "road_panel_stata.dta")

Error in write_dta_(data, normalizePath(path, mustWork = FALSE), version = stata_file_format(version), : Writing failure: A provided name contains an illegal character.

How can I successfully export the data into Stata format?

The output of names(road_panel):

[149] "road_comp_date_new_year_final" "road_comp_date_upg_year_final" "road_comp_date_stip_new_year_final" "road_comp_date_stip_upg_year_final" [153] "year"


Solution

  • A simple fix could be to use foreign::write.dta. It will replace all variable names with x.y to x_y:

    library(foreign)
    write.dta(road_panel, "road_panel_stata.dta")