2

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"

Fuser
  • 47
  • 1
  • 9
  • Hi Fuser. What output do you get with `names(road_panel)`? – Allan Cameron Jun 22 '20 at 17:19
  • Hard to say. Note that Stata 14 supports Unicode. Have you any idea what the character might be? No doubt a stupid question, but equally without more details, an answer is hard. The code might be giving up on the first of several awkward characters. – Nick Cox Jun 22 '20 at 17:21
  • I have 153 variables with long names. I edit the question with the output of names(road_panel). – Fuser Jun 22 '20 at 17:31
  • 2
    It looks like variable 2 and variable 122 contains a period : `"shrid.x"` and `"shrid.y"`, which I don't think is legal in Stata. Also, my understanding is that variable names must have a maximum of 32 characters, which your last variable name exceeds. Perhaps rename these 3 and try again? – Allan Cameron Jun 22 '20 at 20:53
  • Yeah, it worked by replacing ".". Thanks a lot, Allan. – Fuser Jun 23 '20 at 16:31

2 Answers2

4

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")
Zhiqiang Wang
  • 6,206
  • 2
  • 13
  • 27
0

For those that want to use haven. You can simply rename variables removing the illegal character .

Something like this should work

names(road_panel) <- str_replace_all(names(road_panel), pattern = "\\.", replacement = "_"))) # to replace illegal character

write_dta(road_panel, "road_panel_stata.dta")# to save data
Alex
  • 1,207
  • 9
  • 25