问题描述
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")