如何解决使用 R tidyverse 保存并导出到 Stata
library(haven)
> LMI_MENA <- read_dta("Impact on Employment/LMI_MENA.dta")
然后将数据整理如下:
LMI_MENA %>%
pivot_longer(fem_unemployment:male_emp,names_to = "names",values_to = "values") %>%
mutate(Gender = case_when(
str_detect(names,"fem") ~ "Female",str_detect(names,"male") ~ "Male",TRUE ~ "Total"
)) %>%
mutate(names = case_when(
names %in% c("fem_unemployment","male_unemployment","urate") ~ "Unemployment",names %in% c("lfprate","female_lfp","male_lfp") ~ "LaborForceParticipation",names %in% c("fem_emp","male_emp") ~ "Employment"
)) %>%
pivot_wider(names_from = "names",values_from = "values")
我尝试保存编辑后的数据集并将其直接导出到Stata
DF <- data.frame
write.dta(LMI_MENA,file="LMI_MENA_long.dta")
然而,虽然它正确导出,但它没有显示从上面的数据整理中新创建的变量。保存然后导出到 Stata、csv 等的最佳方法是什么?
解决方法
如果您提供可重现的示例,将会有所帮助。看起来您刚刚将原始 Stata 文件保存回 Stata,因为您没有将带有新变量的数据集分配给 R 对象。
在代码的第一行 LMI_MENA %>%
之前,添加 LMI_MENA <- LMI_MENA %>%
。
LMI_MENA <- LMI_MENA %>%
pivot_longer(fem_unemployment:male_emp,names_to = "names",values_to = "values") %>%
mutate(Gender = case_when(
str_detect(names,"fem") ~ "Female",str_detect(names,"male") ~ "Male",TRUE ~ "Total"
)) %>%
mutate(names = case_when(
names %in% c("fem_unemployment","male_unemployment","urate") ~ "Unemployment",names %in% c("lfprate","female_lfp","male_lfp") ~ "LaborForceParticipation",names %in% c("fem_emp","male_emp") ~ "Employment"
)) %>%
pivot_wider(names_from = "names",values_from = "values")
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。