写入失败:提供的名称包含非法字符。将 R 数据保存为 Stata 格式时出错

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

我正在使用 haven 包将 R 数据集写入 Stata 格式。

这是我遇到的错误。

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.

我也尝试了一个稍微不同的代码,但它是一样的。

`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.

如何将数据成功导出为Stata格式?

名字的输出(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]“年”

一个简单的解决方法是使用 foreign::write.dta。它会将所有变量名替换为 x.yx_y:

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

对于那些想要使用 haven 的人。您可以简单地重命名变量,删除非法字符 .

像这样的东西应该可以工作

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