#### libraries --------------
library(ggplot2)
library(cowplot)
library(RColorBrewer)
library(reshape2)
library(forcats)

library(knitr)
library(kableExtra)
library(rlang)
library(wesanderson)
library(haven)
library(margins)#

library(broom)
library(stargazer)
library(scales)
library(dplyr)
library(tidyr)

#### 4  Estimations ####
library(MASS) #MASS:: select clashes with dplyr::select, load late
library(mfx)
library(lmtest)
library(sandwich)
library(fastDummies)

library(data.table)
library(tibble)
library(kableExtra)

est<-readRDS("est.RDS")

## remove reasons
est<-est %>% select(-reason_stud,-reason_comp,-reason_trade,-reason_cust,-reason_inc,- reason_requ,-reason_lab,- reason_partner,-reason_soc,-reason_move_prof,-reason_move_other,-reason_holi,-reason_cult,-reason_inter)
table(a$country, a$age)

#1. type logit (max and min sample x stepwise introduction X aggregate)
#2. type logit (max and min sample x stepwise introduction X country_wise)
#1. langjob logit (max and min sample x stepwise introduction X aggregate)
#2. langjob logit (max and min sample x stepwise introduction X country_wise)


# Info on ind. var.:
#1. empstat: ref. cat. empstat=2
table(est$empstat)
est <- within(est, empstat <- relevel(factor(empstat), ref = "2"))


#2. part (ref cat part=0)
est <- within(est, part <- relevel(factor(part), ref = "0"))
# part=0 No partner
# part=1 partner with German native language
# part=2 partner with other native language


#3. Degree (ref cat part=2)
est <- within(est, degree <- relevel(factor(degree), ref = "2"))

# 0	No degree	
# 1	School leaving certificate which cannot lead to higher education	
# 2	School leaving certificate which can lead to higher education	
# 3	University degree 
# 4	PhD

#4. female: ref. cat. female=0
table(est$female)
est <- within(est, female <- relevel(factor(female), ref = "0"))


stargazer(est, type="text")



#Aggregate 0+1+5 and 3+4
est<-est %>% mutate(degree2=case_when(is.na(.$degree) ~ NA,
                                      .$degree =="0" ~ FALSE,
                                      .$degree =="1" ~ FALSE,
                                      .$degree =="2" ~ FALSE,
                                      .$degree =="3" ~ TRUE,
                                      .$degree =="4" ~ TRUE,
                                      .$degree =="5" ~ FALSE),
                    degree=degree2)

table(est$degree, est$degree2, useNA = "always")


table(est$mreason_lang, useNA="always")

#use only those with completed cases

table(est$complete)

# table(est$type, est$type2, useNA = "always")
est$type2[is.na(est$type2)] = "No answer"

est<-est %>%  mutate(complete=ifelse(complete.cases(est), TRUE, FALSE))

gi<-est[est$complete=="TRUE",]

table(gi$type, gi$type2, useNA = "always")

table(gi$country, gi$empstat)

table(gi$reason_om)


#### Sample shrinkage -------------------
indv <- readRDS("indv.RDS")
indv <-indv %>% mutate(ling=case_when(.$country=="BIH" ~ 0,
                                         .$country=="CZE" ~ 0,
                                         .$country=="ESP" ~ 0,
                                         .$country=="GBR" ~ 1,
                                         .$country=="IDN"~ 0,
                                         .$country=="IND"~ 1,
                                         .$country=="ITA"~ 0,
                                         .$country=="JPN" ~ 0,
                                         .$country=="KOR" ~ 0,
                                         .$country=="MEX"~ 0,
                                         .$country=="NLD"~ 1,
                                         .$country=="POL"~ 0,
                                         .$country=="ROU"~0,
                                         .$country=="UKR"~ 0),
                          europe=case_when(.$country=="BIH" ~ 1,
                                           .$country=="CZE" ~ 0,
                                           .$country=="ESP" ~ 0,
                                           .$country=="GBR" ~ 0,
                                           .$country=="IDN"~ 2,
                                           .$country=="IND"~ 2,
                                           .$country=="ITA"~ 0,
                                           .$country=="JPN" ~ 2,
                                           .$country=="KOR" ~ 2,
                                           .$country=="MEX"~ 2,
                                           .$country=="NLD"~ 0,
                                           .$country=="POL"~ 0,
                                           .$country=="ROU"~0,
                                           .$country=="UKR"~ 1),
                          income=case_when(.$country=="BIH" ~ 1,
                                           .$country=="CZE" ~ 2,
                                           .$country=="ESP" ~ 2,
                                           .$country=="GBR" ~ 2,
                                           .$country=="IDN"~ 0,
                                           .$country=="IND"~ 0,
                                           .$country=="ITA"~ 2,
                                           .$country=="JPN" ~ 2,
                                           .$country=="KOR" ~ 2,
                                           .$country=="MEX"~ 1,
                                           .$country=="NLD"~ 2,
                                           .$country=="POL"~ 2,
                                           .$country=="ROU"~1,
                                           .$country=="UKR"~ 0))

indv1 <- subset(indv,  !is.na(age))
indv2 <- subset(indv1, !is.na(female))
indv3 <- subset(indv2, !is.na(children_d_na))
indv4 <- subset(indv3, !is.na(part))
indv5 <- subset(indv4, !is.na(part))
indv6 <- subset(indv5, !is.na(degree))
indv7 <- subset(indv6, !is.na(risk))
indv8 <- subset(indv7, !is.na(patient))
indv9 <- subset(indv8, !is.na(english))
indv10 <- subset(indv9, !is.na(occupationac))


#### Exclude Education from Main Reason (Uncomment when needed) -----------------
#gi <- as.data.frame(subset(gi, gi$mreason_lang!="Education"))


##### Descriptive table (Table A1: means of individual characteristics by countries) ######

d<-gi

d <- dummy_cols(d, select_columns =c("female", "part", "occupationac"))

d<-d %>% dplyr::select(country, age, female_0, female_1, female_2, children_d_na, 
                       part_0, part_1, part_2, 
                       occupationac_0, occupationac_1, occupationac_2, occupationac_3,
                       occupationac_4, degree, risk, patient, english
                       ) %>%  mutate(one=1)

mean<-aggregate(d[,2:19], list(d$country), mean)  
x<-colMeans(d[,2:19])  
x<-c("Total", x)
mean<-rbind(mean, x)
mean[,2:19] <- sapply(mean[,2:19], function(x) round(as.numeric(x), digits=2))
mean<- mean %>% rename(country=Group.1)

 sum<-aggregate(d[,19], list(d$country), sum)
 x<-sum(d$one)
 x<-c("Total", x)
 sum<-rbind(sum, x)
sum
sum<- sum %>%  rename(country=Group.1, obs=x)

b<-left_join(mean, sum)

b$obs<-as.numeric((b$obs))

b<-b %>%  mutate(country=paste0(country, "\n", "n=(", obs, ")")) %>% 
  dplyr::select(-obs)


row.names(b)<-b$country



# transpose
t_b <- transpose(b)

# get row and colnames in order
colnames(t_b) <- rownames(b)
rownames(t_b) <- colnames(b)

t_b<-rownames_to_column(t_b, var="Variable")

t_b<-filter(t_b, Variable!="country")

t_b$Variable<-as.factor(t_b$Variable)

t_b$Variable<- fct_recode(t_b$Variable,
                    "Age: under 35 years"                                                       = "age" ,
                    "Gender: male"  = "female_0" ,
                    "Gender: female" = "female_1",
                    "Gender: n/a" = "female_2",
                     "No partner" = "part_0"   ,
                     "Partner (native German)"    = "part_1"   ,
                     "Partner (other native)"                                               = "part_2"   ,
                     "Children"                                                      = "children_d_na"   ,
                     "University degree"                          = "degree"   ,
                     "Occ.: low appl."="occupationac_0",
                     "Occ.: high appl./low comm. skills"="occupationac_1",
                     "Occ.: high appl./high comm. skills"="occupationac_2",
                     "Occ.: in education"="occupationac_3",
                     "Occ.: other occ./no answer"="occupationac_4",
                     "Risk attitude"="risk",
                     "Patience"="patient",
                     "English speaker" = "english",
                     "Intern. applic. of education"="applic_gen_d",
                    "Comm. skills: low" = "comm_skills_0",
                    "Comm. skills: high" = "comm_skills_1",
                    "Comm. skills: n/a" = "comm_skills_2"
                    )


t_b %>%  kable(format = "latex",
                digits=2, booktabs=TRUE, linesep = "\\addlinespace",
                caption="Descriptive statistics: means of individual characteristics by countries", 
               align = c("l", "c", "c","c","c","c","c","c","c","c","c","c","c","c","c","c")) %>% 
  kable_styling(latex_options = c("hold_position")) %>% 
    landscape() %>% 
  column_spec(1, width = "4.7cm") %>%
  column_spec(2:16, width= "1cm") 
  

##### Descriptive table (Table  2: means of individual characteristics by country-groups - w/ main reasons) ######

d<-gi

d <- dummy_cols(d, select_columns =c("female", "part", "occupationac"))

d<-d %>% dplyr::select(country, age, female_0, female_1, female_2, children_d_na, 
                       part_0, part_1, part_2, 
                       occupationac_0, occupationac_1, occupationac_2, occupationac_3,
                       occupationac_4, degree, risk, patient, english
                       ) %>%  mutate(one=1)

d<-d %>% mutate(countrygroup=ifelse(country=="ESP" | country=="ITA" | country=="GBR" | country=="NLD" | country=="CZE" | country=="POL" | country=="ROU", "EU",
                                    ifelse(country=="UKR" | country=="BIH", "European (non-EU)", "Non-European" )))

mean<-aggregate(d[,2:19], list(d$countrygroup), mean)  
x<-colMeans(d[,2:19])  
x<-c("Total", x)
mean<-rbind(mean, x)
mean[,2:19] <- sapply(mean[,2:19], function(x) round(as.numeric(x), digits=2))
mean<- mean %>% rename(countrygroup=Group.1)

sum<-aggregate(d[,19], list(d$countrygroup), sum)
x<-sum(d$one)
x<-c("Total", x)
sum<-rbind(sum, x)
sum
sum<- sum %>%  rename(countrygroup=Group.1, obs=x)

b<-left_join(mean, sum)

b$obs<-as.numeric((b$obs))


b<-b %>%  mutate(countrygroup=paste0(countrygroup, "\n", "n=(", obs, ")")) %>% 
  dplyr::select(-obs)


row.names(b)<-b$countrygroup



# transpose
t_b <- transpose(b)

# get row and colnames in order
colnames(t_b) <- rownames(b)
rownames(t_b) <- colnames(b)

t_b<-rownames_to_column(t_b, var="Variable")

t_b<-filter(t_b, Variable!="countrygroup")

t_b$Variable<-as.factor(t_b$Variable)

t_b$Variable<- fct_recode(t_b$Variable,
                          "Age: under 35 years"                                                       = "age" ,
                          "Gender: male"                                                        = "female_0" ,
                          "Gender: female"                                                        = "female_1" ,
                          "Gender: n/a" = "female_2",
                          "No partner"                                                = "part_0"   ,
                          "Partner (native German)"                                                  = "part_1"   ,
                          "Partner (other native)"                                               = "part_2"   ,
                          "Children"                                                      = "children_d_na"   ,
                          "University degree"                                                    = "degree"   ,
                          "Occ.: low appl."="occupationac_0",
                          "Occ.: high appl./low comm. skills"="occupationac_1",
                          "Occ.: high appl./high comm. skills"="occupationac_2",
                          "Occ.: in education"="occupationac_3",
                          "Occ.: other occ./no answer"="occupationac_4",
                          "Risk attitude"="risk",
                          "Patience"="patient",
                          "English speaker" = "english",
                          "Intern. applic. of education"="applic_gen_d",
                          "Comm. skills: low" = "comm_skills_0",
                          "Comm. skills: high" = "comm_skills_1",
                          "Comm. skills: n/a" = "comm_skills_2")


t_b %>%  kable(format = "latex",
               digits=2, booktabs=TRUE, linesep = "\\addlinespace",
               caption="Descriptive statistics: means of individual characteristics by country groups", 
               align = c("l", "c", "c","c","c")) %>% 
  kable_styling(latex_options = c("hold_position")) %>% 
  landscape() %>% 
  column_spec(1, width = "4.7cm") %>%
  column_spec(2:16, width= "2cm") 





##### Descriptive table (Table  2: means of individual characteristics by country-groups - all reasons) ######

d<-est

d <- dummy_cols(d, select_columns =c("female", "part", "occupationac"))

d<-d %>% dplyr::select(country, age, female_0, female_1, female_2, children_d_na, 
                       part_0, part_1, part_2, 
                       occupationac_0, occupationac_1, occupationac_2, 
                       occupationac_3, occupationac_4, degree,risk, patient, english
                       ) %>%  mutate(one=1)

d<-d %>% mutate(countrygroup=ifelse(country=="ESP" | country=="ITA" | country=="GBR" | country=="NLD" | country=="CZE" | country=="POL" | country=="ROU", "EU",
                                    ifelse(country=="UKR" | country=="BIH", "European (non-EU)", "Non-European" )))

mean<-aggregate(d[,2:17], list(d$countrygroup), mean)  
x<-colMeans(d[,2:17])  
x<-c("Total", x)
mean<-rbind(mean, x)
mean[,2:17] <- sapply(mean[,2:17], function(x) round(as.numeric(x), digits=2))
mean<- mean %>% rename(countrygroup=Group.1)

sum<-aggregate(d[,18], list(d$countrygroup), sum)
x<-sum(d$one)
x<-c("Total", x)
sum<-rbind(sum, x)
sum
sum<- sum %>%  rename(countrygroup=Group.1, obs=x)

b<-left_join(mean, sum)

b$obs<-as.numeric((b$obs))
b<-b %>%  mutate(countrygroup=paste0(countrygroup, "\n", "n=(", obs, ")")) %>% 
  dplyr::select(-obs)


row.names(b)<-b$countrygroup



# transpose
t_b <- transpose(b)

# get row and colnames in order
colnames(t_b) <- rownames(b)
rownames(t_b) <- colnames(b)

t_b<-rownames_to_column(t_b, var="Variable")

t_b<-filter(t_b, Variable!="countrygroup")

t_b$Variable<-as.factor(t_b$Variable)

t_b$Variable<- fct_recode(t_b$Variable,
                          "Age: under 35 years"                                                       = "age" ,
                          "Gender: male"                                                        = "female_0" ,
                          "Gender: female"                                                        = "female_1" ,
                          "Gender: n/a" = "female_2",
                          "No partner"                                                = "part_0"   ,
                          "Partner (native German)"                                                  = "part_1"   ,
                          "Partner (other native)"                                               = "part_2"   ,
                          "Children"                                                      = "children_d_na"   ,
                          "University degree"                                                    = "degree"   ,
                          "Occ.: in education"="empstat_1", 
                          "Occ.: in lab. market"="empstat_2", 
                          "Other occ./no answer"="empstat_3",
                          "Risk attitude"="risk",
                          "Patience"="patient",
                          "Intern. applic. of education"="applic_gen")


t_b %>%  kable(format = "latex",
               digits=2, booktabs=TRUE, linesep = "\\addlinespace",
               caption="Descriptive statistics: means of individual characteristics by country groups", 
               align = c("l", "c", "c","c","c")) %>% 
  kable_styling(latex_options = c("hold_position")) %>% 
  landscape() %>% 
  column_spec(1, width = "4.7cm") %>%
  column_spec(2:16, width= "2cm") 





##### Descriptive table (all excluded from 6664) ------------
cleared <- anti_join(indv, gi, by="id_uni")

d<-cleared

#Aggregate 0+1 and 3+4
d<-d %>% mutate(degree2=case_when(is.na(.$degree) ~ NA,
                                      .$degree =="0" ~ FALSE,
                                      .$degree =="1" ~ FALSE,
                                      .$degree =="2" ~ FALSE,
                                      .$degree =="3" ~ TRUE,
                                      .$degree =="4" ~ TRUE,
                                      .$degree =="5" ~ FALSE),
                    degree=degree2)

d <- dummy_cols(d, select_columns =c("female", "part", "occupationac"))

d<-d %>% dplyr::select(country, age, female_0, female_1, female_2, children_d_na, part_0, part_1, part_2, 
                       occupationac_0, occupationac_1, occupationac_2, occupationac_3,
                       occupationac_4, degree, risk, patient, english
                       ) %>%  mutate(one=1)

d<-d %>% mutate(countrygroup=ifelse(country=="ESP" | country=="ITA" | country=="GBR" | country=="NLD" | country=="CZE" | country=="POL" | country=="ROU", "EU",
                                    ifelse(country=="UKR" | country=="BIH", "European (non-EU)", "Non-European" )))

mean<-aggregate(d[,2:19], na.action = na.omit, list(d$countrygroup), mean, na.rm=TRUE)  
x<-colMeans(d[,2:19], na.rm=TRUE)  
x<-c("Total", x)
mean<-rbind(mean, x)
mean[,2:19] <- sapply(mean[,2:19], function(x) round(as.numeric(x), digits=2))
mean<- mean %>% rename(countrygroup=Group.1)

sum<-aggregate(d[,19], list(d$countrygroup), sum)
x<-sum(d$one)
x<-c("Total", x)
sum<-rbind(sum, x)
sum
sum<- sum %>%  rename(countrygroup=Group.1, obs=x)

b<-left_join(mean, sum)

b$obs<-as.numeric((b$obs))

b<-b %>%  mutate(countrygroup=paste0(countrygroup, "\n", "n=(", obs, ")")) %>% 
  dplyr::select(-obs)


row.names(b)<-b$countrygroup



# transpose
t_b <- transpose(b)

# get row and colnames in order
colnames(t_b) <- rownames(b)
rownames(t_b) <- colnames(b)

t_b<-rownames_to_column(t_b, var="Variable")

t_b<-filter(t_b, Variable!="countrygroup")

t_b$Variable<-as.factor(t_b$Variable)

t_b$Variable<- fct_recode(t_b$Variable,
                          "Age: under 35 years"                                                       = "age" ,
                          "Gender: male"                                                        = "female_0" ,
                          "Gender: female"                                                        = "female_1" ,
                          "Gender: n/a" = "female_2",
                          "No partner"                                                = "part_0"   ,
                          "Partner (native German)"                                                  = "part_1"   ,
                          "Partner (other native)"                                               = "part_2"   ,
                          "Children"                                                      = "children_d_na"   ,
                          "University degree"                                                    = "degree"   ,
                          "Occ.: low appl."="occupationac_0",
                          "Occ.: high appl./low comm. skills"="occupationac_1",
                          "Occ.: high appl./high comm. skills"="occupationac_2",
                          "Occ.: in education"="occupationac_3",
                          "Occ.: other occ./no answer"="occupationac_4",
                          "Risk attitude"="risk",
                          "Patience"="patient",
                          "English speaker" = "english")


t_b %>%  kable(format = "latex",
               digits=2, booktabs=TRUE, linesep = "\\addlinespace",
               caption="Descriptive statistics: means of individual characteristics by country groups", 
               align = c("l", "c", "c","c","c")) %>% 
  kable_styling(latex_options = c("hold_position")) %>% 
  landscape() %>% 
  column_spec(1, width = "4.7cm") %>%
  column_spec(2:16, width= "2cm") 


##### Descriptive table (all 6664) ------------
cleared <- indv

d<-cleared

#Aggregate 0+1 and 3+4
d<-d %>% mutate(degree2=case_when(is.na(.$degree) ~ NA,
                                  .$degree =="0" ~ FALSE,
                                  .$degree =="1" ~ FALSE,
                                  .$degree =="2" ~ FALSE,
                                  .$degree =="3" ~ TRUE,
                                  .$degree =="4" ~ TRUE,
                                  .$degree =="5" ~ FALSE),
                degree=degree2)

d <- dummy_cols(d, select_columns =c("female", "part", "occupationac"))

d<-d %>% dplyr::select(country, age, female_0, female_1, female_2, children_d_na, part_0, part_1, part_2, 
                       occupationac_0, occupationac_1, occupationac_2, occupationac_3,
                       occupationac_4, degree, risk, patient, english
) %>%  mutate(one=1)

d<-d %>% mutate(countrygroup=ifelse(country=="ESP" | country=="ITA" | country=="GBR" | country=="NLD" | country=="CZE" | country=="POL" | country=="ROU", "EU",
                                    ifelse(country=="UKR" | country=="BIH", "European (non-EU)", "Non-European" )))

mean<-aggregate(d[,2:19], na.action = na.omit, list(d$countrygroup), mean, na.rm=TRUE)  
x<-colMeans(d[,2:19], na.rm=TRUE)  
x<-c("Total", x)
mean<-rbind(mean, x)
mean[,2:19] <- sapply(mean[,2:19], function(x) round(as.numeric(x), digits=2))
mean<- mean %>% rename(countrygroup=Group.1)

sum<-aggregate(d[,19], list(d$countrygroup), sum)
x<-sum(d$one)
x<-c("Total", x)
sum<-rbind(sum, x)
sum
sum<- sum %>%  rename(countrygroup=Group.1, obs=x)

b<-left_join(mean, sum)

b$obs<-as.numeric((b$obs))

# b<-b %>% mutate(age=paste0(sum_age, " (", round(mean_age, digits = 2) , ")" ),
#                 female=paste0(sum_female, " (", round(mean_female, digits = 2) , ")" ),
#                 part_0=paste0(sum_part_0, " (", round(mean_part_0, digits = 2) , ")" ),
#                 part_1=paste0(sum_part_1, " (", round(mean_part_1, digits = 2) , ")" ),
#                 part_2=paste0(sum_part_2, " (", round(mean_part_2, digits = 2) , ")" ),
#                 children_d_na=paste0(sum_children_d_na, " (", round(mean_children_d_na, digits = 2) , ")" ),
#                 degree=paste0(sum_degree, " (", round(mean_degree, digits = 2) , ")" ),
#                 empstat_1=paste0(sum_empstat_1, " (", round(mean_empstat_1, digits = 2) , ")" ),
#                 empstat_2=paste0(sum_empstat_2, " (", round(mean_empstat_2, digits = 2) , ")" ),
#                 empstat_3=paste0(sum_empstat_3, " (", round(mean_empstat_3, digits = 2) , ")" ),
#                 empstat_4=paste0(sum_empstat_4, " (", round(mean_empstat_4, digits = 2) , ")" ),
#                 risk=paste0("   ", " (", round(mean_risk, digits = 2) , ")" ),
#                 patient=paste0("   ", " (", round(mean_patient, digits = 2) , ")" ),
#                 applic_gen=paste0("   ", " (", round(mean_applic_gen, digits = 2) , ")" ),
#                 mig_phase=paste0(sum_mig_phase, " (", round(mean_mig_phase, digits = 2) , ")" )
#                 ) %>% 
#   rename(obs=sum_one) %>% 
#   dplyr::select(-starts_with("mean_"), -starts_with("sum_")) %>% 
b<-b %>%  mutate(countrygroup=paste0(countrygroup, "\n", "n=(", obs, ")")) %>% 
  dplyr::select(-obs)


row.names(b)<-b$countrygroup



# transpose
t_b <- transpose(b)

# get row and colnames in order
colnames(t_b) <- rownames(b)
rownames(t_b) <- colnames(b)

t_b<-rownames_to_column(t_b, var="Variable")

t_b<-filter(t_b, Variable!="countrygroup")

t_b$Variable<-as.factor(t_b$Variable)

t_b$Variable<- fct_recode(t_b$Variable,
                          "Age: under 35 years"                                                       = "age" ,
                          "Gender: male"                                                        = "female_0" ,
                          "Gender: female"                                                        = "female_1" ,
                          "Gender: n/a" = "female_2",
                          "No partner"                                                = "part_0"   ,
                          "Partner (native German)"                                                  = "part_1"   ,
                          "Partner (other native)"                                               = "part_2"   ,
                          "Children"                                                      = "children_d_na"   ,
                          "University degree"                                                    = "degree"   ,
                          "Occ.: low appl."="occupationac_0",
                          "Occ.: high appl./low comm. skills"="occupationac_1",
                          "Occ.: high appl./high comm. skills"="occupationac_2",
                          "Occ.: in education"="occupationac_3",
                          "Occ.: other occ./no answer"="occupationac_4",
                          "Risk attitude"="risk",
                          "Patience"="patient",
                          "English speaker" = "english")


t_b %>%  kable(format = "latex",
               digits=2, booktabs=TRUE, linesep = "\\addlinespace",
               caption="Descriptive statistics: means of individual characteristics by country groups", 
               align = c("l", "c", "c","c","c")) %>% 
  kable_styling(latex_options = c("hold_position")) %>% 
  landscape() %>% 
  column_spec(1, width = "4.7cm") %>%
  column_spec(2:16, width= "2cm") 


##### T-test to compare full and cleared sample --------------------------------
gitest <- gi %>% 
  mutate(female1 = case_when(female == 1 ~ 1,
                             female == 0 ~ 0,
                             female == 2 ~ 0),
         female0 = case_when(female == 1 ~ 0,
                             female == 0 ~ 1,
                             female == 2 ~ 0),
         part0   = case_when(part == 0 ~ 1,
                             part == 1 ~ 0,
                             part == 2 ~ 0),
         part1   = case_when(part == 1 ~ 1,
                             part == 0 ~ 0,
                             part == 2 ~ 0),
         part2   = case_when(part == 2 ~ 1,
                             part == 0 ~ 0,
                             part == 1 ~ 0),
         occupationac0 = case_when(occupationac == 0 ~ 1,
                                   occupationac == 1 ~ 0,
                                   occupationac == 2 ~ 0,
                                   occupationac == 3 ~ 0,
                                   occupationac == 4 ~ 0),
         occupationac1 = case_when(occupationac == 0 ~ 0,
                                   occupationac == 1 ~ 1,
                                   occupationac == 2 ~ 0,
                                   occupationac == 3 ~ 0,
                                   occupationac == 4 ~ 0),
         occupationac2 = case_when(occupationac == 0 ~ 0,
                                   occupationac == 1 ~ 0,
                                   occupationac == 2 ~ 1,
                                   occupationac == 3 ~ 0,
                                   occupationac == 4 ~ 0),
         occupationac3 = case_when(occupationac == 0 ~ 0,
                                   occupationac == 1 ~ 0,
                                   occupationac == 2 ~ 0,
                                   occupationac == 3 ~ 1,
                                   occupationac == 4 ~ 0),
         occupationac4 = case_when(occupationac == 0 ~ 0,
                                   occupationac == 1 ~ 0,
                                   occupationac == 2 ~ 0,
                                   occupationac == 3 ~ 0,
                                   occupationac == 4 ~ 1),
         degree1       = case_when(degree2 == 0 ~ 0,
                                   degree2 == 1 ~ 1),
         english1      = case_when(english == 0 ~ 0,
                                   english == 1 ~ 1)
         ) 

indvtest <- indv %>% 
  mutate(female1 = case_when(female == 1 ~ 1,
                             female == 0 ~ 0,
                             female == 2 ~ 0),
         female0 = case_when(female == 1 ~ 0,
                             female == 0 ~ 1,
                             female == 2 ~ 0),
         part0   = case_when(part == 0 ~ 1,
                             part == 1 ~ 0,
                             part == 2 ~ 0),
         part1   = case_when(part == 1 ~ 1,
                             part == 0 ~ 0,
                             part == 2 ~ 0),
         part2   = case_when(part == 2 ~ 1,
                             part == 0 ~ 0,
                             part == 1 ~ 0),
         occupationac0 = case_when(occupationac == 0 ~ 1,
                                   occupationac == 1 ~ 0,
                                   occupationac == 2 ~ 0,
                                   occupationac == 3 ~ 0,
                                   occupationac == 4 ~ 0),
         occupationac1 = case_when(occupationac == 0 ~ 0,
                                   occupationac == 1 ~ 1,
                                   occupationac == 2 ~ 0,
                                   occupationac == 3 ~ 0,
                                   occupationac == 4 ~ 0),
         occupationac2 = case_when(occupationac == 0 ~ 0,
                                   occupationac == 1 ~ 0,
                                   occupationac == 2 ~ 1,
                                   occupationac == 3 ~ 0,
                                   occupationac == 4 ~ 0),
         occupationac3 = case_when(occupationac == 0 ~ 0,
                                   occupationac == 1 ~ 0,
                                   occupationac == 2 ~ 0,
                                   occupationac == 3 ~ 1,
                                   occupationac == 4 ~ 0),
         occupationac4 = case_when(occupationac == 0 ~ 0,
                                   occupationac == 1 ~ 0,
                                   occupationac == 2 ~ 0,
                                   occupationac == 3 ~ 0,
                                   occupationac == 4 ~ 1),
         degree1       = case_when(degree == 0 ~ 0,
                                   degree == 1 ~ 0,
                                   degree == 2 ~ 0,
                                   degree == 3 ~ 1,
                                   degree == 4 ~ 1,
                                   degree == 5 ~ 0),
         english1      = case_when(english == 0 ~ 0,
                                   english == 1 ~ 1)
  ) 

t.test(indvtest$degree1, gitest$degree1, var.equal = FALSE)


##### Analyze missings in mreason_lang -----------------------------------------
mlangmiss <- as.data.frame(subset(gi, gi$mreason_lang=="No answer"))
mlangcomp <- as.data.frame(subset(gi, gi$mreason_lang!="No answer"))
t.test(mlangcomp$age, mlangmiss$age, var.equal = FALSE)

##### #### Analyze correlation between reason for migration and language learning motive ------
# gimig <- as.data.frame(subset(gi, mreason_mig1 >= 0))
# 
# table(gimig$mainrea_educlab)
# 
# educlab <- table(gimig$mreason_mig1[gimig$mreason_lang=="Other migration"])
# library(openxlsx)
# write.xlsx(educlab, 'tables/2.xlsx')
# educlab <- table(gimig$mainrea_other, gimig$mreason_lang)
# educlab <- as.data.frame(educlab)
# educlab <- reshape(educlab, idvar = "Var1", timevar = "Var2", direction = "wide")
# names(educlab) <- sub(".*\\.", "", names(educlab))
# library(openxlsx)
# write.xlsx(educlab, 'tables/educ.xlsx')

######## Binary Probit #########################################

#### 1 Binomial (logit) type #### 
#### Exclude edcuation from motives --------------------------------------------
giwo <- as.data.frame(subset(gi, gi$mreason_lang!="Education"))

#### 1 a1 w/o FE ####

type_full<-as.formula("type ~ factor(age)+female+children_d_na+part+occupationac+degree+risk+patient+english")
                      #+mig_phase")
type<-glm(formula = type_full, family = binomial(link = "probit"), data = gi)
type_het <- print(coeftest(type, vcovCL), digits=6)
nobs(type)


# Marginal effects (Average marginal effects)
type_ame <- probitmfx(formula = type_full,
                      data=gi,
                      atmean = FALSE, 
                      robust = TRUE, 
                      clustervar1 = NULL, clustervar2 = NULL, 
                      start = NULL, control = list())
# average marginal effects with heteroscedasticity-robust White standard errors
print(type_ame)


# Percent correctly predicted values
type_predict<-(table(true = gi$type, pred = round(fitted(type)))[1,1]+table(true = gi$type, pred = round(fitted(type)))[2,2])/nobs(type)*100 


# McFadden's Pseudo R-squared
type_baseline <- update(type, formula= type ~ 1)
type_McFadden <- 1 - as.vector(logLik(type)/logLik(type_baseline))
type_McFadden 


#### 1 a2 w FE ####
table(gi$age)

type_full_fe<-as.formula("type ~ factor(age)+female+children_d_na+part+occupationac+degree+risk+patient+english+country")#+mig_phase")
type_fe<-glm(formula = type_full_fe, family = binomial(link = "probit"), data = gi)
type_fe_het <- print(coeftest(type_fe, vcovCL), digits=6)
nobs(type_fe)


# Marginal effects (Average marginal effects)
type_fe_ame <- probitmfx(formula = type_full_fe,
                         data=gi,
                         atmean = FALSE, 
                         robust = TRUE, 
                         clustervar1 = NULL, clustervar2 = NULL, 
                         start = NULL, control = list())
# average marginal effects with heteroscedasticity-robust White standard errors
print(type_fe_ame)


# Percent correctly predicted values
type_fe_predict<-(table(true = gi$type, pred = round(fitted(type_fe)))[1,1]+table(true = gi$type, pred = round(fitted(type_fe)))[2,2])/nobs(type_fe)*100 

# McFadden's Pseudo R-squared
type_fe_baseline <- update(type_fe, formula= type ~ 1)
type_fe_McFadden <- 1 - as.vector(logLik(type_fe)/logLik(type_fe_baseline))
type_fe_McFadden 


#### 1 a2 w FE w/o education ####
type_full_fe<-as.formula("type ~ factor(age)+female+children_d_na+part+occupationac+degree+risk+patient+english+country")#+mig_phase")
type_fe_wo<-glm(formula = type_full_fe, family = binomial(link = "probit"), data = giwo)
type_fe_het_wo <- print(coeftest(type_fe_wo, vcovCL), digits=6)
nobs(type_fe_wo)


# Marginal effects (Average marginal effects)
type_fe_ame_wo <- probitmfx(formula = type_full_fe,
                         data=giwo,
                         atmean = FALSE, 
                         robust = TRUE, 
                         clustervar1 = NULL, clustervar2 = NULL, 
                         start = NULL, control = list())
# average marginal effects with heteroscedasticity-robust White standard errors
print(type_fe_ame_wo)


# Percent correctly predicted values
type_fe_predict_wo <- (table(true = giwo$type, pred = round(fitted(type_fe_wo)))[1,1]+table(true = giwo$type, pred = round(fitted(type_fe_wo)))[2,2])/nobs(type_fe_wo)*100 

# McFadden's Pseudo R-squared
type_fe_baseline_wo <- update(type_fe_wo, formula= type ~ 1)
type_fe_McFadden_wo <- 1 - as.vector(logLik(type_fe_wo)/logLik(type_fe_baseline_wo))
type_fe_McFadden_wo 


#### 1 a3 w/o FE + c####

type_full_c<-as.formula("type ~ factor(age)+female+children_d_na+part+occupationac+degree+risk+patient+english+factor(ling)+factor(europe)+factor(income)+ltodist+ivrdist") #+mig_phase")
type_c<-glm(formula = type_full_c, family = binomial(link = "probit"), data = gi)
type_c_het <- print(coeftest(type_c, vcovCL), digits=6)
nobs(type_c)


# Marginal effects (Average marginal effects)
type_c_ame <- probitmfx(formula = type_full_c,
                      data=gi,
                      atmean = FALSE, 
                      robust = TRUE, 
                      clustervar1 = NULL, clustervar2 = NULL, 
                      start = NULL, control = list())
# average marginal effects with heteroscedasticity-robust White standard errors
print(type_c_ame)


# Percent correctly predicted values
type_c_predict<-(table(true = gi$type, pred = round(fitted(type_c)))[1,1]+table(true = gi$type, pred = round(fitted(type_c)))[2,2])/nobs(type_c)*100 


# McFadden's Pseudo R-squared
type_c_baseline <- update(type_c, formula= type ~ 1)
type_c_McFadden <- 1 - as.vector(logLik(type_c)/logLik(type_c_baseline))
type_c_McFadden 








#### 1 a3 w/o FE + c w/o education ####

type_full_c<-as.formula("type ~ factor(age)+female+children_d_na+part+occupationac+degree+risk+patient+english+factor(ling)+factor(europe)+factor(income)+ltodist+ivrdist") #+mig_phase")
type_c_wo<-glm(formula = type_full_c, family = binomial(link = "probit"), data = giwo)
type_c_het_wo <- print(coeftest(type_c_wo, vcovCL), digits=6)
nobs(type_c_wo)


# Marginal effects (Average marginal effects)
type_c_ame_wo <- probitmfx(formula = type_full_c,
                        data=giwo,
                        atmean = FALSE, 
                        robust = TRUE, 
                        clustervar1 = NULL, clustervar2 = NULL, 
                        start = NULL, control = list())
# average marginal effects with heteroscedasticity-robust White standard errors
print(type_c_ame_wo)


# Percent correctly predicted values
type_c_predict_wo <- (table(true = giwo$type, pred = round(fitted(type_c_wo)))[1,1]+table(true = giwo$type, pred = round(fitted(type_c_wo)))[2,2])/nobs(type_c_wo)*100 


# McFadden's Pseudo R-squared
type_c_baseline_wo <- update(type_c_wo, formula= type ~ 1)
type_c_McFadden_wo <- 1 - as.vector(logLik(type_c_wo)/logLik(type_c_baseline_wo))
type_c_McFadden_wo 








#### 1 a3 Output (Average Marginal Effects) ####
stargazer(type_ame$fit, 
          type_fe_ame$fit, 
          type_c_ame$fit, 
          coef = list(type_ame$mfxest[,1], 
                      type_fe_ame$mfxest[,1],
                      type_c_ame$mfxest[,1]),
          se = list(type_ame$mfxest[,2],
                    type_fe_ame$mfxest[,2],
                    type_c_ame$mfxest[,2]),
          header=TRUE,
          p.auto=FALSE,
          style="default",
          nobs=TRUE,
          align=TRUE, 
          no.space=TRUE, 
          single.row=FALSE,
          model.names = FALSE,
          dep.var.labels   = "Human capital investment",
          covariate.labels= c(   "Age: under 35 years",
                                  "Gender: female",
                                  "Gender: n/a",
                                  "Children",
                                  "Partner (native German)",
                                  "Partner (other native)",
                                  "Occ.: high appl./low comm. skills",
                                  "Occ.: high appl./high comm. skills",
                                  "Occ.: in education",
                                  "Occ.: other occ./no answer",
                                  "University degree",
                                  "Risk attitude",
                                  "Patience",
                                  "English speaker",
                                  "Germanic lang.",
                                 "European (Non-EU)",
                                 "Non-European",
                                 "Upper-middle income",
                                 "High income",
                                 "Cultural distance: LTO",
                                 "Cultural distance: IVR"),
          omit = c("Constant", "country", "empstat4"),
          font.size = "small",
          add.lines = list(c("Country FE", "No", "Yes", "No"),
                           c("McFadden Pseudo R2", round(type_McFadden, digits=2), round(type_fe_McFadden, digits=2), round(type_c_McFadden, digits=2)),
                           c("Percent. correctly predicted", round(type_predict, digits=1), round(type_fe_predict, digits=1), round(type_c_predict, digits=1) )),
          omit.table.layout = "n",
          omit.stat = c("aic", "ll"))


#### 1 a3 Output (Average Marginal Effects) ####
stargazer(type_fe_ame_wo$fit, 
          type_c_ame_wo$fit, 
          type_fe_ame$fit, 
          type_c_ame$fit, 
          coef = list(type_fe_ame_wo$mfxest[,1],
                      type_c_ame_wo$mfxest[,1],
                      type_fe_ame$mfxest[,1],
                      type_c_ame$mfxest[,1]),
          se = list(type_fe_ame_wo$mfxest[,2],
                    type_c_ame_wo$mfxest[,2],
                    type_fe_ame$mfxest[,2],
                    type_c_ame$mfxest[,2]),
          header=TRUE,
          p.auto=FALSE,
          style="default",
          nobs=TRUE,
          align=TRUE, 
          no.space=TRUE, 
          single.row=FALSE,
          model.names = FALSE,
          dep.var.labels   = "Human capital investment",
          covariate.labels= c(   "Age: under 35 years",
                                 "Gender: female",
                                 "Gender: n/a",
                                 "Children",
                                 "Partner (native German)",
                                 "Partner (other native)",
                                 "Occ.: high appl./low comm. skills",
                                 "Occ.: high appl./high comm. skills",
                                 "Occ.: in education",
                                 "Occ.: other occ./no answer",
                                 "University degree",
                                 "Risk attitude",
                                 "Patience",
                                 "English speaker",
                                 "Germanic lang.",
                                 "European (Non-EU)",
                                 "Non-European",
                                 "Upper-middle income",
                                 "High income",
                                 "Cultural distance: LTO",
                                 "Cultural distance: IVR"),
          omit = c("Constant", "country", "empstat4"),
          font.size = "small",
          add.lines = list(c("Country FE", "Yes", "No", "Yes", "No"),
                           c("McFadden Pseudo R2", 
                             round(type_fe_McFadden_wo, digits=2), 
                             round(type_c_McFadden_wo, digits=2),
                             round(type_fe_McFadden, digits=2), 
                             round(type_c_McFadden, digits=2)),
                           c("Percent. correctly predicted", 
                             round(type_fe_predict_wo, digits=1), 
                             round(type_c_predict_wo, digits=1),
                             round(type_fe_predict, digits=1), 
                             round(type_c_predict, digits=1))),
          omit.table.layout = "n",
          omit.stat = c("aic", "ll"))




#### 1 b subsamples ###

#### 1 a3 Output (Average Marginal Effects) ####
stargazer(type_fe_ame$fit, 
          type_c_ame_nodeg$fit,
          type_c_ame_deg$fit,
          type_ame_nodeg$fit,
          type_ame_deg$fit,
          coef = list(type_fe_ame$mfxest[,1],
                      type_c_ame_nodeg$mfxest[,1],
                      type_c_ame_deg$mfxest[,1],
                      type_ame_nodeg$mfxest[,1],
                      type_ame_deg$mfxest[,1]
),
          se = list(type_fe_ame$mfxest[,2],
                    type_c_ame_nodeg$mfxest[,2],
                    type_c_ame_deg$mfxest[,2],
                    type_ame_nodeg$mfxest[,2],
                    type_ame_deg$mfxest[,2]
),
          header=TRUE,
          style="default",
          dep.var.labels   = "Human capital investment",
          covariate.labels= c(   "Age: under 35 years",
                                 "Gender: female",
                                 "Gender: n/a",
                                 "Children",
                                 "Partner (native German)",
                                 "Partner (other native)",
                                 "Occ.: in education",
                                 "Other occ./no answer",
                                 "University degree",
                                 "Risk attitude",
                                 "Patience",
                                 "English speaker",
                                 "Intern. applic. of education: high",
                                 "Comm. skills in prof. life: high",
                                 "Comm. skills in prof. life: n/a"),
          column.labels = c("Whole sample", "No uni. deg.", "Uni. deg.", "No uni. deg.", "Uni deg."),
          nobs=TRUE,
          no.space=TRUE, 
          single.row=TRUE,
          model.names = FALSE,
          omit = c("Constant", "country", "empstat4"),
          font.size = "small",
          add.lines = list(c("Country FE", "Yes", "Yes", "Yes", "Yes", "Yes"),
                           c("McFadden Pseudo R2", 
                             round(type_fe_McFadden, digits=2), 
                             round(type_c_McFadden_nodeg, digits=2), 
                             round(type_c_McFadden_deg, digits=2), 
                             round(type_McFadden_nodeg, digits=2), 
                             round(type_McFadden_deg, digits=2)),
                           c("Percent. correctly predicted", 
                             round(type_fe_predict, digits=1), 
                             round(type_c_predict_nodeg, digits=1), 
                             round(type_c_predict_deg, digits=1), 
                             round(type_predict_nodeg, digits=1), 
                             round(type_predict_deg, digits=1) )),
          omit.table.layout = "n",
          omit.stat = c("aic", "ll"))




#### 1 a2 w FE + FE:age ####
table(gi$age)

type_full_fea<-as.formula("type ~ factor(age)+female+children_d_na+part+occupationac+degree+risk+patient+english+country+country:factor(age)")#+mig_phase")
type_fea<-glm(formula = type_full_fea, family = binomial(link = "probit"), data = gi)
type_fe_heta <- print(coeftest(type_fea, vcovCL), digits=6)
nobs(type_fea)


# Marginal effects (Average marginal effects)
type_fe_amea <- probitmfx(formula = type_full_fea,
                         data=gi,
                         atmean = FALSE, 
                         robust = TRUE, 
                         clustervar1 = NULL, clustervar2 = NULL, 
                         start = NULL, control = list())
# average marginal effects with heteroscedasticity-robust White standard errors
print(type_fe_amea)


# Percent correctly predicted values
type_fe_predicta<-(table(true = gi$type, pred = round(fitted(type_fea)))[1,1]+table(true = gi$type, pred = round(fitted(type_fea)))[2,2])/nobs(type_fea)*100 

# McFadden's Pseudo R-squared
type_fe_baselinea <- update(type_fea, formula= type ~ 1)
type_fe_McFaddena <- 1 - as.vector(logLik(type_fea)/logLik(type_fe_baselinea))
type_fe_McFaddena 



#### 1 a2 w FE + FE:age + FE:gender ####
table(gi$age)

type_full_feag <-as.formula("type ~ factor(age)+female+children_d_na+part+occupationac+degree+risk+patient+english+country+country:factor(age)+country:female")#+mig_phase")
type_feag<-glm(formula = type_full_feag, family = binomial(link = "probit"), data = gi)
type_fe_hetag <- print(coeftest(type_feag, vcovCL), digits=6)
nobs(type_feag)


# Marginal effects (Average marginal effects)
type_fe_ameag <- probitmfx(formula = type_full_feag,
                         data=gi,
                         atmean = FALSE, 
                         robust = TRUE, 
                         clustervar1 = NULL, clustervar2 = NULL, 
                         start = NULL, control = list())
# average marginal effects with heteroscedasticity-robust White standard errors
print(type_fe_ameag)


# Percent correctly predicted values
type_fe_predictag<-(table(true = gi$type, pred = round(fitted(type_feag)))[1,1]+table(true = gi$type, pred = round(fitted(type_feag)))[2,2])/nobs(type_feag)*100 

# McFadden's Pseudo R-squared
type_fe_baselineag <- update(type_feag, formula= type ~ 1)
type_fe_McFaddenag <- 1 - as.vector(logLik(type_feag)/logLik(type_fe_baselineag))
type_fe_McFaddenag 



#### 1 a3 Output (Average Marginal Effects) ####
stargazer(type_fe_ame$fit, 
          type_fe_amea$fit,
          type_fe_ameag$fit,
          coef = list(type_fe_ame$mfxest[,1], 
                      type_fe_amea$mfxest[,1],
                      type_fe_ameag$mfxest[,1]),
          se = list(type_fe_ame$mfxest[,2],
                    type_fe_amea$mfxest[,2],
                    type_fe_ameag$mfxest[,2]),
          header=TRUE,
          p.auto=FALSE,
          style="default",
          nobs=TRUE,
          align=TRUE, 
          no.space=TRUE, 
          single.row=FALSE,
          model.names = FALSE,
          dep.var.labels   = "Human capital investment",
          covariate.labels= c(   "Age: under 35 years",
                                 "Gender: female",
                                 "Gender: n/a",
                                 "Children",
                                 "Partner (native German)",
                                 "Partner (other native)",
                                 "Occ.: high appl./low comm. skills",
                                 "Occ.: high appl./high comm. skills",
                                 "Occ.: in education",
                                 "Occ.: other occ./no answer",
                                 "University degree",
                                 "Risk attitude",
                                 "Patience",
                                 "English speaker"
                                 ),
          omit = c("Constant", "country"),
          font.size = "small",
          add.lines = list(c("Country FE", "Yes", "Yes", "Yes"),
                           c("McFadden Pseudo R2", 
                             round(type_fe_McFadden, digits=2), 
                             round(type_fe_McFaddena, digits=2), 
                             round(type_fe_McFaddenag, digits=2)),
                           c("Percent. correctly predicted", 
                             round(type_fe_predict, digits=1), 
                             round(type_fe_predicta, digits=1), 
                             round(type_fe_predictag, digits=1))),
          omit.table.layout = "n",
          omit.stat = c("aic", "ll"))



#### 1 b1 Female w FE ####

gi_female<-gi[gi$female==1,]

type_full_fe_gender<-as.formula("type ~ factor(age)+children_d_na+part+occupationac+degree+risk+patient+english+country") #+mig_phase
type_female<-glm(formula = type_full_fe_gender, family = binomial(link = "probit"), data = gi_female)
type_female_het <- print(coeftest(type_female, vcovCL), digits=6)
nobs(type_female)


# Marginal effects (Average marginal effects)
type_female_ame <- probitmfx(formula = type_full_fe_gender,
                             data=gi_female,
                             atmean = FALSE, 
                             robust = TRUE, 
                             clustervar1 = NULL, clustervar2 = NULL, 
                             start = NULL, control = list())
# average marginal effects with heteroscedasticity-robust White standard errors
print(type_female_ame)


# Percent correctly predicted values
type_female_predict <-(table(true = gi_female$type, pred = round(fitted(type_female)))[1,1]+table(true = gi_female$type, pred = round(fitted(type_female)))[2,2])/nobs(type_female)*100 


# McFadden's Pseudo R-squared
type_female_baseline <- update(type_female, formula= type ~ 1)
type_female_McFadden <- 1 - as.vector(logLik(type_female)/logLik(type_female_baseline))
type_female_McFadden 

#### 1 b2 Male w FE ####

gi_male<-gi[gi$female==0,]

type_full_fe_gender<-as.formula("type ~ factor(age)+children_d_na+part+occupationac+degree+risk+patient+english+country") #+mig_phase
type_male<-glm(formula = type_full_fe_gender, family = binomial(link = "probit"), data = gi_male)
type_male_het <- print(coeftest(type_male, vcovCL), digits=6)
nobs(type_male)


# Marginal effects (Average marginal effects)
type_male_ame <- probitmfx(formula = type_full_fe_gender,
                           data=gi_male,
                           atmean = FALSE, 
                           robust = TRUE, 
                           clustervar1 = NULL, clustervar2 = NULL, 
                           start = NULL, control = list())
# average marginal effects with heteroscedasticity-robust White standard errors
print(type_male_ame)


# Percent correctly predicted values
type_male_predict <-(table(true = gi_male$type, pred = round(fitted(type_male)))[1,1]+table(true = gi_male$type, pred = round(fitted(type_male)))[2,2])/nobs(type_male)*100 

# McFadden's Pseudo R-squared
type_male_baseline <- update(type_male, formula= type ~ 1)
type_male_McFadden <- 1 - as.vector(logLik(type_male)/logLik(type_male_baseline))
type_male_McFadden 




#### 1 b3 Age young w FE ####


table(gi$age)



gi_agey<-gi[gi$age=="TRUE",]

type_full_fe_age<-as.formula("type ~ female+children_d_na+part+occupationac+degree+risk+patient+english+country") #+mig_phase
type_agey<-glm(formula = type_full_fe_age, family = binomial(link = "probit"), data = gi_agey)
type_agey_het <- print(coeftest(type_agey, vcovCL), digits=6)
nobs(type_agey)


# Marginal effects (Average marginal effects)
type_agey_ame <- probitmfx(formula = type_full_fe_age,
                             data=gi_agey,
                             atmean = FALSE, 
                             robust = TRUE, 
                             clustervar1 = NULL, clustervar2 = NULL, 
                             start = NULL, control = list())
# average marginal effects with heteroscedasticity-robust White standard errors
print(type_agey_ame)


# Percent correctly predicted values
type_agey_predict <-(table(true = gi_agey$type, pred = round(fitted(type_agey)))[1,1]+table(true = gi_agey$type, pred = round(fitted(type_agey)))[2,2])/nobs(type_agey)*100 


# McFadden's Pseudo R-squared
type_agey_baseline <- update(type_agey, formula= type ~ 1)
type_agey_McFadden <- 1 - as.vector(logLik(type_agey)/logLik(type_agey_baseline))
type_agey_McFadden 








#### 1 b4 Age older w FE ####


table(gi$age)



gi_ageo<-gi[gi$age!="TRUE",]

type_full_fe_age<-as.formula("type ~ female+children_d_na+part+occupationac+degree+risk+patient+english+country") #+mig_phase
type_ageo<-glm(formula = type_full_fe_age, family = binomial(link = "probit"), data = gi_ageo)
type_ageo_het <- print(coeftest(type_ageo, vcovCL), digits=6)
nobs(type_ageo)


# Marginal effects (Average marginal effects)
type_ageo_ame <- probitmfx(formula = type_full_fe_age,
                           data=gi_ageo,
                           atmean = FALSE, 
                           robust = TRUE, 
                           clustervar1 = NULL, clustervar2 = NULL, 
                           start = NULL, control = list())
# average marginal effects with heteroscedasticity-robust White standard errors
print(type_ageo_ame)


# Percent correctly predicted values
type_ageo_predict <-(table(true = gi_ageo$type, pred = round(fitted(type_ageo)))[1,1]+table(true = gi_ageo$type, pred = round(fitted(type_ageo)))[2,2])/nobs(type_ageo)*100 


# McFadden's Pseudo R-squared
type_ageo_baseline <- update(type_ageo, formula= type ~ 1)
type_ageo_McFadden <- 1 - as.vector(logLik(type_ageo)/logLik(type_ageo_baseline))
type_ageo_McFadden 











#### 1 b5 no Uni_deg w FE ####
gi_nodeg <- as.data.frame(subset(gi, degree==FALSE))

type_full<-as.formula("type ~ factor(age)+female+children_d_na+part+occupationac+risk+patient+english+country") #+mig_phase")
type_nodeg<-glm(formula = type_full, family = binomial(link = "probit"), data = gi_nodeg)
type_hetnodeg <- print(coeftest(type_nodeg, vcovCL), digits=6)
nobs(type_nodeg)


# Marginal effects (Average marginal effects)
type_ame_nodeg <- probitmfx(formula = type_full,
                              data=gi_nodeg,
                              atmean = FALSE, 
                              robust = TRUE, 
                              clustervar1 = NULL, clustervar2 = NULL, 
                              start = NULL, control = list())
# average marginal effects with heteroscedasticity-robust White standard errors
print(type_ame_nodeg)


# Percent correctly predicted values
type_predict_nodeg<-(table(true = gi_nodeg$type, pred = round(fitted(type_nodeg)))[1,1]+table(true = gi_nodeg$type, pred = round(fitted(type_nodeg)))[2,2])/nobs(type_nodeg)*100 


# McFadden's Pseudo R-squared
type_baseline_nodeg <- update(type_nodeg, formula= type ~ 1)
type_McFadden_nodeg <- 1 - as.vector(logLik(type_nodeg)/logLik(type_baseline_nodeg))
type_McFadden_nodeg 



#### 1 b6 Uni_deg w FE ####
gi_deg   <- as.data.frame(subset(gi, degree==TRUE)) 

type_full<-as.formula("type ~ factor(age)+female+children_d_na+part+occupationac+risk+patient+english+country") #+mig_phase")
type_deg<-glm(formula = type_full, family = binomial(link = "probit"), data = gi_deg)
type_hetdeg <- print(coeftest(type_deg, vcovCL), digits=6)
nobs(type_deg)


# Marginal effects (Average marginal effects)
type_ame_deg <- probitmfx(formula = type_full,
                            data=gi_deg,
                            atmean = FALSE, 
                            robust = TRUE, 
                            clustervar1 = NULL, clustervar2 = NULL, 
                            start = NULL, control = list())
# average marginal effects with heteroscedasticity-robust White standard errors
print(type_ame_deg)


# Percent correctly predicted values
type_predict_deg<-(table(true = gi_deg$type, pred = round(fitted(type_deg)))[1,1]+table(true = gi_deg$type, pred = round(fitted(type_deg)))[2,2])/nobs(type_deg)*100 


# McFadden's Pseudo R-squared
type_baseline_deg <- update(type_deg, formula= type ~ 1)
type_McFadden_deg <- 1 - as.vector(logLik(type_deg)/logLik(type_baseline_deg))
type_McFadden_deg 




#### 1 b6 Output AME FE Gender/ age / degree ####

stargazer(type_female_ame$fit, 
          type_male_ame$fit,
          type_agey_ame$fit,
          type_ageo_ame$fit,
          type_ame_nodeg$fit,
          type_ame_deg$fit,
          coef = list(type_female_ame$mfxest[,1], 
                      type_male_ame$mfxest[,1],
                      type_agey_ame$mfxest[,1],
                      type_ageo_ame$mfxest[,1],
                      type_ame_nodeg$mfxest[,1],
                      type_ame_deg$mfxest[,1]),
          se = list(type_female_ame$mfxest[,2],
                    type_male_ame$mfxest[,2],
                    type_agey_ame$mfxest[,2],
                    type_ageo_ame$mfxest[,2],
                    type_ame_nodeg$mfxest[,2],
                    type_ame_deg$mfxest[,2]),
          header=TRUE,
          p.auto=FALSE,
          style="default",
          nobs=TRUE,
          align=TRUE, 
          no.space=TRUE, 
          single.row=FALSE,
          model.names = FALSE,
          dep.var.labels   = "Humancapital investment",
          column.labels = c("female", "male", "Age: under 35 years", "Age: 35 and more years", "no Uni. deg.", "Uni. deg."),
          covariate.labels= c(   "Age: under 35 years",
                                 "Gender: female",
                                 "Gender: n/a",
                                 "Children",
                                 "Partner (native German)",
                                 "Partner (other native)",
                                 "Occ.: high appl./low comm. skills",
                                 "Occ.: high appl./high comm. skills",
                                 "Occ.: in education",
                                 "Occ.: other occ./no answer",
                                 "University degree",
                                 "Risk attitude",
                                 "Patience",
                                 "English speaker"),
          omit = c("Constant", "country"),
          font.size = "small",
          add.lines = list(c("Country FE", "Yes", "Yes","Yes", "Yes", "Yes", "Yes"),
                           c("McFadden Pseudo R2", 
                             round(type_female_McFadden, digits=2), 
                             round(type_male_McFadden, digits=2), 
                             round(type_agey_McFadden, digits=2), 
                             round(type_ageo_McFadden, digits=2),
                             round(type_McFadden_nodeg, digits=2),
                             round(type_McFadden_deg, digits=2)),
                           c("Percent. correctly predicted", 
                             round(type_female_predict, digits=1), 
                             round(type_male_predict, digits=1), 
                             round(type_agey_predict, digits=1), 
                             round(type_ageo_predict, digits=1),
                             round(type_predict_nodeg, digits=1),
                             round(type_predict_deg, digits=1))),
          omit.stat = c("aic", "ll"),
          omit.table.layout = "n")


#### 1 c Country-wise ####


#### 1 c1 Countries ####

TOT<-probitmfx(formula = type_full_fe, data=gi, atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
BIH<-probitmfx(formula = type_full, data=gi[gi$country=="BIH",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
CZE<-probitmfx(formula = type_full, data=gi[gi$country=="CZE",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
ESP<-probitmfx(formula = type_full, data=gi[gi$country=="ESP",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
GBR<-probitmfx(formula = type_full, data=gi[gi$country=="GBR",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
ITA<-probitmfx(formula = type_full, data=gi[gi$country=="ITA",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
JPN<-probitmfx(formula = type_full, data=gi[gi$country=="JPN",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
KOR<-probitmfx(formula = type_full, data=gi[gi$country=="KOR",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
NLD<-probitmfx(formula = type_full, data=gi[gi$country=="NLD",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
POL<-probitmfx(formula = type_full, data=gi[gi$country=="POL",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
ROU<-probitmfx(formula = type_full, data=gi[gi$country=="ROU",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
IND<-probitmfx(formula = type_full, data=gi[gi$country=="IND",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
IDN<-probitmfx(formula = type_full, data=gi[gi$country=="IDN",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
UKR<-probitmfx(formula = type_full, data=gi[gi$country=="UKR",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
MEX<-probitmfx(formula = type_full, data=gi[gi$country=="MEX",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())




stargazer(TOT$fit, 
          BIH$fit,
          CZE$fit, 
          ESP$fit,
          GBR$fit, 
          ITA$fit,
          JPN$fit, 
          KOR$fit,
          NLD$fit, 
          POL$fit,
          ROU$fit, 
          IND$fit,
          IDN$fit, 
          UKR$fit,
          MEX$fit, 
          coef = list(TOT$mfxest[,1], 
                      BIH$mfxest[,1],
                      CZE$mfxest[,1], 
                      ESP$mfxest[,1],
                      GBR$mfxest[,1], 
                      ITA$mfxest[,1],
                      JPN$mfxest[,1], 
                      KOR$mfxest[,1],
                      NLD$mfxest[,1], 
                      POL$mfxest[,1],
                      ROU$mfxest[,1], 
                      IND$mfxest[,1],
                      IDN$mfxest[,1], 
                      UKR$mfxest[,1],
                      MEX$mfxest[,1]),
          se = list(TOT$mfxest[,2],
                    BIH$mfxest[,2],
                    CZE$mfxest[,2],
                    ESP$mfxest[,2],
                    GBR$mfxest[,2],
                    ITA$mfxest[,2],
                    JPN$mfxest[,2],
                    KOR$mfxest[,2],
                    NLD$mfxest[,2],
                    POL$mfxest[,2],
                    ROU$mfxest[,2],
                    IND$mfxest[,2],
                    IDN$mfxest[,2],
                    UKR$mfxest[,2],
                    MEX$mfxest[,2]),
          column.labels = c("TOT", "BIH", "CZE", "ESP",  "GBR", "ITA", "JPN", "KOR", "NLD", "POL", "ROU", "IND", "IDN", "UKR", "MEX"),
          header=FALSE,
          style="default",
          dep.var.labels   = "Humancapital investment",
          covariate.labels= c(    "Age: under 35 years",
                                  "Gender: female",
                                  "Gender: n/a",
                                  "Children",
                                  "Partner (native German)",
                                  "Partner (other native)",
                                  "Occ.: in education", 
                                  "Other occ./no answer",
                                  "University degree",
                                  "Risk attitude",
                                  "Patience",
                                  "Intern. applic. of education"
                                  ),
          nobs=TRUE,
          align=FALSE, 
          no.space=TRUE, 
          single.row=TRUE,
          model.names = FALSE,
          omit = c("Constant", "country"),
          font.size = "small",
          add.lines = list(c("Country FE", "Yes", "No", "No","No","No","No","No","No","No","No","No","No","No","No","No")),
          omit.stat = c("aic", "ll"))


TOT_type<-tidy(TOT)  %>% filter(term != "(Intercept)") %>% mutate(model = "Total")
BIH_type<-tidy(BIH)  %>% filter(term != "(Intercept)") %>% mutate(model = "BIH (n=126)")
CZE_type<-tidy(CZE)  %>% filter(term != "(Intercept)") %>% mutate(model = "CZE (n=311)")
ESP_type<-tidy(ESP)  %>% filter(term != "(Intercept)") %>% mutate(model = "ESP (n=467)")
GBR_type<-tidy(GBR)  %>% filter(term != "(Intercept)") %>% mutate(model = "GBR (n=339)")
ITA_type<-tidy(ITA)  %>% filter(term != "(Intercept)") %>% mutate(model = "ITA (n=218)")
JPN_type<-tidy(JPN)  %>% filter(term != "(Intercept)") %>% mutate(model = "JPN (n=196)")
KOR_type<-tidy(KOR)  %>% filter(term != "(Intercept)") %>% mutate(model = "KOR (n=215)")
NLD_type<-tidy(NLD)  %>% filter(term != "(Intercept)") %>% mutate(model = "NLD (n=68)")
POL_type<-tidy(POL)  %>% filter(term != "(Intercept)") %>% mutate(model = "POL (n=138)")
ROU_type<-tidy(ROU)  %>% filter(term != "(Intercept)") %>% mutate(model = "ROU (n=223)")
IND_type<-tidy(IND)  %>% filter(term != "(Intercept)") %>% mutate(model = "IND (n=406)")
IDN_type<-tidy(IDN)  %>% filter(term != "(Intercept)") %>% mutate(model = "IDN (n=539)")
UKR_type<-tidy(UKR)  %>% filter(term != "(Intercept)") %>% mutate(model = "UKR (n=512)")
MEX_type<-tidy(MEX)  %>% filter(term != "(Intercept)") %>% mutate(model = "MEX (n=316)")

gi %>% count(country) %>% arrange(-n)

country_l_type<-rbind(TOT_type, 
                      ESP_type, GBR_type, CZE_type, ITA_type, POL_type, ROU_type, NLD_type,
                      BIH_type,  UKR_type, 
                      MEX_type, IND_type, IDN_type,
                      KOR_type, JPN_type)

country_l_type<-country_l_type %>% mutate(sign=ifelse(model=="Total" & p.value<0.05, TRUE, FALSE)) %>% 
  group_by(term) %>% mutate(sign_5=max(sign), sign=ifelse(sign_5==0, "P>0.05 (aggr. model)", "P<0.05 (aggr. model)"), sign=as.factor(sign)) %>% filter(model!="Total")




#### 1 c2a Country groups ####
eu_sw<-probitmfx(formula = type_full_fe, data=gi[gi$country=="ESP" | gi$country=="ITA"| gi$country=="GBR" | gi$country=="NLD" ,],
                 atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
                 start = NULL, control = list())

eu_e<-probitmfx(formula = type_full_fe, data=gi[gi$country=="CZE" | gi$country=="POL" | gi$country=="ROU",],
                atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
                start = NULL, control = list())

eur<- probitmfx(formula = type_full_fe, data=gi[gi$country=="UKR" | gi$country=="BIH",], 
                atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
                start = NULL, control = list())

noneu_d<-probitmfx(formula = type_full_fe, data=gi[gi$country=="JPN" | gi$country=="KOR" | gi$country=="MEX",],
                   atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL,
                   start = NULL, control = list())

noneu_ld<-probitmfx(formula = type_full_fe, data=gi[gi$country=="IDN" | gi$country=="IND" ,], 
                   atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
                   start = NULL, control = list())

eu<-probitmfx(formula = type_full_fe, data=gi[gi$country=="ESP" | gi$country=="ITA"|gi$country=="NLD" | gi$country=="GBR"|gi$country=="CZE" | gi$country=="POL" | gi$country=="ROU",], 
              atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
              start = NULL, control = list())

noneu<- probitmfx(formula = type_full_fe, data=gi[gi$country=="MEX" | gi$country=="IDN" | gi$country=="IND"|gi$country=="JPN" | gi$country=="KOR"|gi$country=="UKR" | gi$country=="BIH",], 
                  atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
                  start = NULL, control = list())


stargazer(eu_sw$fit, 
          eu_e$fit,
          eur$fit, 
          noneu_d$fit,
          noneu_ld$fit, 
          eu$fit,
          noneu$fit, 
          coef = list(eu_sw$mfxest[,1], 
                      eu_e$mfxest[,1],
                      eur$mfxest[,1], 
                      noneu_d$mfxest[,1],
                      noneu_ld$mfxest[,1], 
                      eu$mfxest[,1],
                      noneu$mfxest[,1]),
          se = list(eu_sw$mfxest[,2], 
                    eu_e$mfxest[,2],
                    eur$mfxest[,2], 
                    noneu_d$mfxest[,2],
                    noneu_ld$mfxest[,2], 
                    eu$mfxest[,2],
                    noneu$mfxest[,2]),
          column.labels = c("ESP, ITA, GBR, NLD", "CZE, POL, ROU", "UKR, BIH",  "JPN, KOR, MEX", "IND, IDN", "EU", "Non-EU"),
          header=FALSE,
          style="default",
          dep.var.labels   = "Human capital investment",
          covariate.labels= c(    "Age: under 35 years",
                                  "Gender: female",
                                  "Gender: n/a",
                                  "Children",
                                  "Partner (native German)",
                                  "Partner (other native)",
                                  "Occ.: in education", 
                                  "Other occ./no answer",
                                  "University degree",
                                  "Risk attitude",
                                  "Patience",
                                  "Intern. applic. of education"
                                  ),
          nobs=TRUE,
          align=FALSE, 
          no.space=TRUE, 
          single.row=FALSE,
          model.names = FALSE,
          omit = c("Constant", "country"),
          font.size = "small",
          add.lines = list(c("Country FE", "Yes", "Yes","Yes","Yes","Yes","Yes","Yes")),
          omit.stat = c("aic", "ll"),
          omit.table.layout = "n")



eu_sw_type<-tidy(eu_sw)  %>% filter(term != "(Intercept)") %>%  mutate(model = "ESP, ITA, GBR, NLD (n=1118)")
nrow(gi[gi$country=="ESP" | gi$country=="ITA"| gi$country=="GBR" | gi$country=="NLD" ,])

eu_e_type<-tidy(eu_e)  %>% filter(term != "(Intercept)") %>% mutate(model = "CZE, POL, ROU (n=704)")
nrow(gi[gi$country=="CZE" | gi$country=="POL" | gi$country=="ROU",])



eur_type<-tidy(eur)  %>% filter(term != "(Intercept)") %>%  mutate(model = "UKR, BIH (n=683)")
nrow(gi[gi$country=="UKR" | gi$country=="BIH",])


noneu_d_type<-tidy(noneu_d)  %>% filter(term != "(Intercept)") %>% mutate(model = "JPN, KOR, MEX (n=848)")
nrow(gi[gi$country=="JPN" | gi$country=="KOR" | gi$country=="MEX",])


noneu_ld_type<-tidy(noneu_ld)  %>% filter(term != "(Intercept)") %>%  mutate(model = "IND, IDN (n=1003)")
nrow(gi[gi$country=="IDN" | gi$country=="IND",])


eu_type<-tidy(eu)  %>% filter(term != "(Intercept)") %>% mutate(model = "EU (n=1822)")
nrow(gi[gi$country=="ESP" | gi$country=="ITA"|gi$country=="NLD" | gi$country=="GBR"|gi$country=="CZE" | gi$country=="POL" | gi$country=="ROU",])


noneu_type<-tidy(noneu)  %>% filter(term != "(Intercept)") %>% mutate(model = "Non-EU (n=2534)")
nrow(gi[gi$country=="MEX" | gi$country=="IDN" | gi$country=="IND"|gi$country=="JPN" | gi$country=="KOR"|gi$country=="UKR" | gi$country=="BIH",])


countrygr_l_type<-rbind(TOT_type, eu_sw_type, eu_e_type, eur_type, noneu_d_type, noneu_ld_type, eu_type, noneu_type)

countrygr_l_type<-countrygr_l_type %>% mutate(sign=ifelse(model=="Total" & p.value<0.05, TRUE, FALSE)) %>% 
  group_by(term) %>% mutate(sign_5=max(sign), sign=ifelse(sign_5==0, "P>0.05 (aggr. model)", "P<0.05 (aggr. model)"), sign=as.factor(sign)) %>% filter(model!="Total")



#### 1 c2b Country characteristics ####
germ<-probitmfx(formula = type_full_fe, data=gi[gi$country=="NLD" | gi$country=="GBR" | gi$country=="IND",],
                atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
                start = NULL, control = list())



ngerm<-probitmfx(formula = type_full_fe, data=gi[gi$country=="ESP" | gi$country=="ITA" | gi$country=="CZE" |gi$country=="ROU" 
                                                 | gi$country=="BIH" | gi$country=="MEX"| gi$country=="IND"| gi$country=="UKR"
                                                 | gi$country=="JPN" | gi$country=="KOR" | gi$country=="POL", ],
                    atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
                    start = NULL, control = list())

hi<-probitmfx(formula = type_full_fe, data=gi[gi$country=="ESP" | gi$country=="ITA"| gi$country=="GBR" | gi$country=="NLD" | gi$country=="CZE" | gi$country=="POL" | gi$country=="JPN"| gi$country=="KOR" ,],
              atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
              start = NULL, control = list())

umi<-probitmfx(formula = type_full_fe, data=gi[gi$country=="ROU" | gi$country=="BIH" | gi$country=="MEX",],
                   atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL,
                   start = NULL, control = list())

lmi<-probitmfx(formula = type_full_fe, data=gi[gi$country=="IDN" | gi$country=="IND"| gi$country=="UKR" ,], 
                    atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
                    start = NULL, control = list())

mi<-probitmfx(formula = type_full_fe, data=gi[gi$country=="IDN" | gi$country=="IND"| gi$country=="UKR" | gi$country=="ROU" | gi$country=="BIH" | gi$country=="MEX" ,], 
              atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
              start = NULL, control = list())


eur<- probitmfx(formula = type_full_fe, data=gi[gi$country=="UKR" | gi$country=="BIH",], 
                atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
                start = NULL, control = list())

eu<-probitmfx(formula = type_full_fe, data=gi[gi$country=="ESP" | gi$country=="ITA"|gi$country=="NLD" | gi$country=="GBR"|gi$country=="CZE" | gi$country=="POL" | gi$country=="ROU",], 
              atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
              start = NULL, control = list())

noneur<- probitmfx(formula = type_full_fe, data=gi[gi$country=="MEX" | gi$country=="IDN" | gi$country=="IND"|gi$country=="JPN" | gi$country=="KOR",], 
                  atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
                  start = NULL, control = list())

noneu<- probitmfx(formula = type_full_fe, data=gi[gi$country=="MEX" | gi$country=="IDN" | gi$country=="IND"|gi$country=="JPN" | gi$country=="KOR"|gi$country=="UKR" | gi$country=="BIH",], 
                  atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
                  start = NULL, control = list())

cultclose<- probitmfx(formula = type_full_fe, data=gi[gi$country=="JPN" | gi$country=="BIH" | gi$country=="CZE"|gi$country=="IDN" | gi$country=="UKR"|gi$country=="KOR" | gi$country=="ITA",], 
                      atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
                      start = NULL, control = list())

cultdist<- probitmfx(formula = type_full_fe, data=gi[gi$country=="MEX" | gi$country=="IND" | gi$country=="ESP"|gi$country=="NLD" | gi$country=="ROU"|gi$country=="POL" | gi$country=="GBR",], 
                  atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
                  start = NULL, control = list())


stargazer(germ$fit, 
          ngerm$fit,
          umi$fit, 
          lmi$fit,
          hi$fit, 
          eu$fit,
          eur$fit,
          noneur$fit,
          cultclose$fit,
          cultdist$fit,
          coef = list(germ$mfxest[,1], 
                      ngerm$mfxest[,1],
                      lmi$mfxest[,1], 
                      umi$mfxest[,1],
                      mi$mfxest[,1],
                      hi$mfxest[,1], 
                      eu$mfxest[,1],
                       eur$mfxest[,1],
                       noneur$mfxest[,1],
                       cultclose$mfxest[,1],
                       cultdist$mfxest[,1]
                     ),
          se = list(germ$mfxest[,2], 
                    ngerm$mfxest[,2],
                     lmi$mfxest[,2], 
                     umi$mfxest[,2],
                    hi$mfxest[,2], 
                    eu$mfxest[,2],
                      eur$mfxest[,2],
                      noneur$mfxest[,2],
                      cultclose$mfxest[,2],
                      cultdist$mfxest[,2]
                    ),
          column.labels = c("Germanic", "Non-Germanic",
                            "Lower-middle income", "Upper-middle income", 
                            "High income", "EU", 
                            "European (non-EU)", "Non-European",
                            "Culturally close", "Culturally far"
                            ),
          header=TRUE,
          p.auto=FALSE,
          style="default",
          nobs=TRUE,
          align=TRUE, 
          no.space=TRUE, 
          single.row=FALSE,
          model.names = FALSE,
          dep.var.labels   = "Human capital investment",
          covariate.labels= c(   "Age: under 35 years",
                                 "Gender: female",
                                 "Gender: n/a",
                                 "Children",
                                 "Partner (native German)",
                                 "Partner (other native)",
                                 "Occ.: high appl./low comm. skills",
                                 "Occ.: high appl./high comm. skills",
                                 "Occ.: in education",
                                 "Occ.: other occ./no answer",
                                 "University degree",
                                 "Risk attitude",
                                 "Patience",
                                 "English speaker"),
          omit = c("Constant", "country"),
          font.size = "small",
          add.lines = list(c("Country FE", "Yes", "Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes")),
          omit.stat = c("aic", "ll"),
          omit.table.layout = "n")



germ_type<-tidy(germ)  %>% filter(term != "(Intercept)") %>%  mutate(model = "Germanic")
ngerm_type<-tidy(ngerm)  %>% filter(term != "(Intercept)") %>%  mutate(model = "Non-Germanic")

umi_type<-tidy(umi)  %>% filter(term != "(Intercept)") %>%  mutate(model = "Upper-middle income")
lmi_type<-tidy(lmi)  %>% filter(term != "(Intercept)") %>%  mutate(model = "Lower-middle income")
hi_type<-tidy(hi)  %>% filter(term != "(Intercept)") %>%  mutate(model = "High income")
mi_type<-tidy(mi)  %>% filter(term != "(Intercept)") %>%  mutate(model = "Middle income")

eu_type<-tidy(eu)  %>% filter(term != "(Intercept)") %>% mutate(model = "EU")
noneu_type<-tidy(noneu)  %>% filter(term != "(Intercept)") %>% mutate(model = "Non-EU (European)")
eur_type<-tidy(eur)  %>% filter(term != "(Intercept)") %>% mutate(model = "Non-EU (European)")
noneur_type<-tidy(noneur)  %>% filter(term != "(Intercept)") %>% mutate(model = "Non-EU (non-European)")

cultclose_type<-tidy(cultclose)  %>% filter(term != "(Intercept)") %>%  mutate(model = "Cuturally close")
cultdist_type<-tidy(cultdist)  %>% filter(term != "(Intercept)") %>%  mutate(model = "Culturally dist.")


countrygr_l_type<-rbind(TOT_type, ngerm_type, germ_type, lmi_type, umi_type, hi_type, eu_type, eur_type, noneur_type, cultclose_type, cultdist_type)

countrygr_l_type<-countrygr_l_type %>% mutate(sign=ifelse(model=="Total" & p.value<0.05, TRUE, FALSE)) %>% 
  group_by(term) %>% mutate(sign_5=max(sign), sign=ifelse(sign_5==0, "P>0.05 (aggr. model)", "P<0.05 (aggr. model)"), sign=as.factor(sign)) %>% filter(model!="Total")



countrygr_l_type<-rbind(TOT_type, ngerm_type, germ_type, lmi_type, umi_type, hi_type, eu_type, eur_type, noneur_type, cultclose_type, cultdist_type)

countrygr_l_type<-countrygr_l_type %>% mutate(sign=ifelse(model=="Total" & p.value<0.05, TRUE, FALSE)) %>% 
  group_by(term) %>% mutate(sign_5=max(sign), sign=ifelse(sign_5==0, "P>0.05 (aggr. model)", "P<0.05 (aggr. model)"), sign=as.factor(sign)) %>% filter(model!="Total")





p_countrygroup<-dwplot(subset(countrygr_l_type,
                             (countrygr_l_type$term=="factor(age)TRUE" |
                              countrygr_l_type$term=="female1" | 
                              countrygr_l_type$term=="children_d_naTRUE" | 
                              countrygr_l_type$term=="part1" | 
                              countrygr_l_type$term=="part2" | 
                              countrygr_l_type$term=="occupationac1" | 
                              countrygr_l_type$term=="occupationac2" | 
                              countrygr_l_type$term=="occupationac3" | 
                              countrygr_l_type$term=="degreeTRUE" |
                              countrygr_l_type$term=="risk" | 
                              countrygr_l_type$term=="patient" |
                              countrygr_l_type$term=="englishTRUE"
                             )),
                       vline = geom_vline(xintercept = 0, colour = "grey60", linetype = 2), dodge_size= 0.7,
                       dot_args = list(aes(shape =as.factor(sign)), size=4)) +
  scale_x_continuous(limits = c(-0.7, 0.35))+
  scale_y_discrete(   labels=c("factor(age)TRUE" = "Age: under 35 years",
                               female1 = "Gender: female",                       
                               children_d_naTRUE = "Children", 
                               "part1" = "Partner (native German)",                       
                               "part2" = "Partner (other native)",
                               degreeTRUE= "University degree",
                               "occupationac1" = "Occ.: high appl./low comm. skills",
                               "occupationac2" = "Occ.: high appl./high comm. skills",
                               "occupationac3" = "Occ.: in education",
                               risk = "Risk attitude", 
                               patient = "Patience",
                               "englishTRUE" = "English speaker"
  ))+
  xlab("AME")+
  theme(legend.title = element_blank())+
  scale_color_grey(guide=guide_legend(reverse = TRUE))


pdf("../graphics/invest_countrychar.pdf", paper="a4", width = 12, height = 14) 
p_countrygroup
dev.off()


#### 1 c3 leave one country out ####

TOT<-probitmfx(formula = type_full_fe, data=gi, atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
BIH<-probitmfx(formula = type_full_fe, data=gi[gi$country!="BIH",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
CZE<-probitmfx(formula = type_full_fe, data=gi[gi$country!="CZE",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
ESP<-probitmfx(formula = type_full_fe, data=gi[gi$country!="ESP",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
GBR<-probitmfx(formula = type_full_fe, data=gi[gi$country!="GBR",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
ITA<-probitmfx(formula = type_full_fe, data=gi[gi$country!="ITA",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
JPN<-probitmfx(formula = type_full_fe, data=gi[gi$country!="JPN",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
KOR<-probitmfx(formula = type_full_fe, data=gi[gi$country!="KOR",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
NLD<-probitmfx(formula = type_full_fe, data=gi[gi$country!="NLD",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
POL<-probitmfx(formula = type_full_fe, data=gi[gi$country!="POL",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
ROU<-probitmfx(formula = type_full_fe, data=gi[gi$country!="ROU",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
IND<-probitmfx(formula = type_full_fe, data=gi[gi$country!="IND",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
IDN<-probitmfx(formula = type_full_fe, data=gi[gi$country!="IDN",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
UKR<-probitmfx(formula = type_full_fe, data=gi[gi$country!="UKR",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
MEX<-probitmfx(formula = type_full_fe, data=gi[gi$country!="MEX",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())

stargazer(TOT$fit, 
          BIH$fit,
          CZE$fit, 
          ESP$fit,
          GBR$fit, 
          ITA$fit,
          JPN$fit, 
          KOR$fit,
          NLD$fit, 
          POL$fit,
          ROU$fit, 
          IND$fit,
          IDN$fit, 
          UKR$fit,
          MEX$fit, 
          coef = list(TOT$mfxest[,1], 
                      BIH$mfxest[,1],
                      CZE$mfxest[,1], 
                      ESP$mfxest[,1],
                      GBR$mfxest[,1], 
                      ITA$mfxest[,1],
                      JPN$mfxest[,1], 
                      KOR$mfxest[,1],
                      NLD$mfxest[,1], 
                      POL$mfxest[,1],
                      ROU$mfxest[,1], 
                      IND$mfxest[,1],
                      IDN$mfxest[,1], 
                      UKR$mfxest[,1],
                      MEX$mfxest[,1]),
          se = list(TOT$mfxest[,2],
                    BIH$mfxest[,2],
                    CZE$mfxest[,2],
                    ESP$mfxest[,2],
                    GBR$mfxest[,2],
                    ITA$mfxest[,2],
                    JPN$mfxest[,2],
                    KOR$mfxest[,2],
                    NLD$mfxest[,2],
                    POL$mfxest[,2],
                    ROU$mfxest[,2],
                    IND$mfxest[,2],
                    IDN$mfxest[,2],
                    UKR$mfxest[,2],
                    MEX$mfxest[,2]),
          column.labels = c("TOT", "BIH", "CZE", "ESP",  "GBR", "ITA", "JPN", "KOR", "NLD", "POL", "ROU", "IND", "IDN", "UKR", "MEX"),
          header=FALSE,
          style="default",
          dep.var.labels   = "Humancapital investment",
          covariate.labels= c(    "Age: under 35 years",
                                  "Gender: female",
                                  "Gender: n/a",
                                  "Children",
                                  "Partner (native German)",
                                  "Partner (other native)",
                                  "Occ.: in education", 
                                  "Occ.: not in lab. market",
                                  "University degree",
                                  "Risk attitude",
                                  "Patience",
                                  "Intern. applic. of education"
                                  ),
          nobs=TRUE,
          align=TRUE, 
          no.space=TRUE, 
          single.row=TRUE,
          model.names = FALSE,
          omit = c("Constant", "country", "empstat4"),
          font.size = "small",
          add.lines = list(c("Country FE", "Yes", "Yes", "Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes")),
          notes= "Average marginal effects. Heteroscedasticity robust White standard errors in parentheses.",
          omit.stat = c("aic", "ll"))


TOT_type<-tidy(TOT)  %>% filter(term != "(Intercept)") %>% mutate(model = "Total")
BIH_type<-tidy(BIH)  %>% filter(term != "(Intercept)") %>% mutate(model = "BIH (n=110)")
CZE_type<-tidy(CZE)  %>% filter(term != "(Intercept)") %>% mutate(model = "CZE (n=280)")
ESP_type<-tidy(ESP)  %>% filter(term != "(Intercept)") %>% mutate(model = "ESP (n=395)")
GBR_type<-tidy(GBR)  %>% filter(term != "(Intercept)") %>% mutate(model = "GBR (n=274)")
ITA_type<-tidy(ITA)  %>% filter(term != "(Intercept)") %>% mutate(model = "ITA (n=186)")
JPN_type<-tidy(JPN)  %>% filter(term != "(Intercept)") %>% mutate(model = "JPN (n=183)")
KOR_type<-tidy(KOR)  %>% filter(term != "(Intercept)") %>% mutate(model = "KOR (n=189)")
NLD_type<-tidy(NLD)  %>% filter(term != "(Intercept)") %>% mutate(model = "NLD (n=60)")
POL_type<-tidy(POL)  %>% filter(term != "(Intercept)") %>% mutate(model = "POL (n=121)")
ROU_type<-tidy(ROU)  %>% filter(term != "(Intercept)") %>% mutate(model = "ROU (n=197)")
IND_type<-tidy(IND)  %>% filter(term != "(Intercept)") %>% mutate(model = "IND (n=373)")
IDN_type<-tidy(IDN)  %>% filter(term != "(Intercept)") %>% mutate(model = "IDN (n=485)")
UKR_type<-tidy(UKR)  %>% filter(term != "(Intercept)") %>% mutate(model = "UKR (n=458)")
MEX_type<-tidy(MEX)  %>% filter(term != "(Intercept)") %>% mutate(model = "MEX (n=281)")

gi %>% count(country) %>% arrange(-n)

country_l_type<-rbind(TOT_type, 
                      ESP_type, GBR_type, CZE_type, ITA_type, POL_type, ROU_type, NLD_type,
                      BIH_type,  UKR_type, 
                      MEX_type, IND_type, IDN_type,
                      KOR_type, JPN_type)

country_l_type<-country_l_type %>% mutate(sign=ifelse(model=="Total" & p.value<0.05, TRUE, FALSE)) %>% 
  group_by(term) %>% mutate(sign_5=max(sign), sign=ifelse(sign_5==0, "P>0.05 (aggr. model)", "P<0.05 (aggr. model)"), sign=as.factor(sign)) 




#### 2 Binary logit langjob ####
gi<-est[est$complete=="TRUE",]
gi$langjob<-ifelse(!is.na(gi$langjob), (gi$langjob-6)*(-1), NA)

table(gi$langjob, gi$country)
table(applic=gi[gi$type==TRUE,]$applic_gen, langjob=gi[gi$type==TRUE,]$langjob)

mean(gi$langjob)
median(gi$langjob)
table(gi$langjob)

gi<-gi %>% mutate(langjob_d=ifelse(langjob>3, TRUE, ifelse(is.na(langjob), NA, FALSE)))
mean(gi$langjob_d)

langjob_full_fe<-as.formula("langjob_d ~ factor(age)+female+children_d_na+part+occupationac+degree+risk+patient+english+country") #+mig_phase
langjob_full_type_fe<-as.formula("langjob_d ~ type + factor(age)+female+children_d_na+part+occupationac+degree+risk+patient+english+country") #+mig_phase
langjob_full_type_fe_g<-as.formula("langjob_d ~ type + factor(age)+children_d_na+part+occupationac+degree+risk+patient+english+country") #+mig_phase
langjob_full_type2_fe<-as.formula("langjob_d ~ type2+factor(age)+female+children_d_na+part+occupationac+degree+risk+patient+english+country") #+mig_phase
langjob_full_type2_fe_g<-as.formula("langjob_d ~ type2+factor(age)+female+children_d_na+part+occupationac+degree+risk+patient+english+country") #+mig_phase
langjob_full_type2_c<-as.formula("langjob_d ~ type+factor(age)+female+children_d_na+part+occupationac+degree+risk+patient+english+factor(ling)+factor(europe)+factor(income)+ltodist+ivrdist") #+mig_phase
langjob_full_type2_c_g<-as.formula("langjob_d ~ type+factor(age)+female+children_d_na+part+occupationac+degree+risk+patient+english+factor(ling)+factor(europe)+factor(income)+ltodist+ivrdist") #+mig_phase
langjob_full_type2<-as.formula("langjob_d ~ type2+factor(age)+female+children_d_na+part+occupationac+degree+risk+patient+english") #+mig_phase
langjob_full_type2_g<-as.formula("langjob_d ~ type2+factor(age)+female+children_d_na+part+occupationac+degree+risk+patient+english") #+mig_phase

#### 2 a1 base langjob ####
langjob_fe<-glm(formula = langjob_full_fe, family = binomial(link = "probit"), data = gi)
langjob_fe_het <- print(coeftest(langjob_fe, vcovCL), digits=6)
nobs(langjob_fe)


# Marginal effects (Average marginal effects)
langjob_fe_ame <- probitmfx(formula = langjob_full_fe,
                         data=gi,
                         atmean = FALSE, 
                         robust = TRUE, 
                         clustervar1 = NULL, clustervar2 = NULL, 
                         start = NULL, control = list())
# average marginal effects with heteroscedasticity-robust White standard errors
print(langjob_fe_ame)


# Percent correctly predicted values
langjob_fe_predict<- (table(true = gi$langjob_d, pred = round(fitted(langjob_fe)))[1,1]+table(true = gi$langjob_d, pred = round(fitted(langjob_fe)))[2,2] ) /nobs(langjob_fe) *100 # 71,4 % correctly predicted values

# McFadden's Pseudo R-squared
langjob_fe_baseline <- update(langjob_fe, formula= langjob_d ~ 1)
langjob_fe_McFadden <- 1 - as.vector(logLik(langjob_fe)/logLik(langjob_fe_baseline))
langjob_fe_McFadden 




#### 2 a2 type ####

langjob_type_fe<-glm(formula = langjob_full_type_fe, family = binomial(link = "probit"), data = gi)
langjob_type_fe_het <- print(coeftest(langjob_type_fe, vcovCL), digits=6)
nobs(langjob_type_fe)


# Marginal effects (Average marginal effects)
langjob_type_fe_ame <- probitmfx(formula = langjob_full_type_fe,
                            data=gi,
                            atmean = FALSE, 
                            robust = TRUE, 
                            clustervar1 = NULL, clustervar2 = NULL, 
                            start = NULL, control = list())
# average marginal effects with heteroscedasticity-robust White standard errors
print(langjob_type_fe_ame)


# Percent correctly predicted values
langjob_type_fe_predict<- (table(true = gi$langjob_d, pred = round(fitted(langjob_type_fe)))[1,1]+table(true = gi$langjob_d, pred = round(fitted(langjob_type_fe)))[2,2] ) /nobs(langjob_type_fe) *100# 71,4 % correctly predicted values


# McFadden's Pseudo R-squared
langjob_type_fe_baseline <- update(langjob_type_fe, formula= langjob_d ~ 1)
langjob_type_fe_McFadden <- 1 - as.vector(logLik(langjob_type_fe)/logLik(langjob_type_fe_baseline))
langjob_type_fe_McFadden 


#### 2 a2 type w/o education ####

langjob_type_fe_wo<-glm(formula = langjob_full_type_fe, family = binomial(link = "probit"), data = giwo)
langjob_type_fe_het_wo <- print(coeftest(langjob_type_fe_wo, vcovCL), digits=6)
nobs(langjob_type_fe_wo)


# Marginal effects (Average marginal effects)
langjob_type_fe_ame_wo <- probitmfx(formula = langjob_full_type_fe,
                                 data=giwo,
                                 atmean = FALSE, 
                                 robust = TRUE, 
                                 clustervar1 = NULL, clustervar2 = NULL, 
                                 start = NULL, control = list())
# average marginal effects with heteroscedasticity-robust White standard errors
print(langjob_type_fe_ame_wo)


# Percent correctly predicted values
langjob_type_fe_predict_wo <- (table(true = giwo$langjob_d, pred = round(fitted(langjob_type_fe_wo)))[1,1]+table(true = giwo$langjob_d, pred = round(fitted(langjob_type_fe_wo)))[2,2] ) /nobs(langjob_type_fe_wo) *100# 71,4 % correctly predicted values


# McFadden's Pseudo R-squared
langjob_type_fe_baseline_wo <- update(langjob_type_fe_wo, formula= langjob_d ~ 1)
langjob_type_fe_McFadden_wo <- 1 - as.vector(logLik(langjob_type_fe_wo)/logLik(langjob_type_fe_baseline_wo))
langjob_type_fe_McFadden_wo 


#### 2 a3 type2 ####
table(gi$type2)
langjob_type2_fe<-glm(formula = langjob_full_type2_fe, family = binomial(link = "probit"), data = gi[gi$type2!="No answer",])
langjob_type2_fe_het <- print(coeftest(langjob_type2_fe, vcovCL), digits=6)
nobs(langjob_type2_fe)


# Marginal effects (Average marginal effects)
langjob_type2_fe_ame <- probitmfx(formula = langjob_full_type2_fe,
                                  data = gi[gi$type2!="No answer",],
                                 atmean = FALSE, 
                                 robust = TRUE, 
                                 clustervar1 = NULL, clustervar2 = NULL, 
                                 start = NULL, control = list())
# average marginal effects with heteroscedasticity-robust White standard errors
print(langjob_type2_fe_ame)


# Percent correctly predicted values
langjob_type2_fe_predict<- (table(true = gi[gi$type2!="No answer",]$langjob_d, pred = round(fitted(langjob_type2_fe)))[1,1]+table(true =gi[gi$type2!="No answer",]$langjob_d, pred = round(fitted(langjob_type2_fe)))[2,2] ) /nobs(langjob_type2_fe) *100 # 71,4 % correctly predicted values


# McFadden's Pseudo R-squared
langjob_type2_fe_baseline <- update(langjob_type2_fe, formula= langjob_d ~ 1)
langjob_type2_fe_McFadden <- 1 - as.vector(logLik(langjob_type2_fe)/logLik(langjob_type2_fe_baseline))
langjob_type2_fe_McFadden 


#### 2 a4 type2 + c ####
table(gi$type2)
langjob_type2_c<-glm(formula = langjob_full_type2_c, family = binomial(link = "probit"), data = gi)
langjob_type2_c_het <- print(coeftest(langjob_type2_c, vcovCL), digits=6)
nobs(langjob_type2_c)


# Marginal effects (Average marginal effects)
langjob_type2_c_ame <- probitmfx(formula = langjob_full_type2_c,
                                  data = gi,
                                  atmean = FALSE, 
                                  robust = TRUE, 
                                  clustervar1 = NULL, clustervar2 = NULL, 
                                  start = NULL, control = list())
# average marginal effects with heteroscedasticity-robust White standard errors
print(langjob_type2_c_ame)


# Percent correctly predicted values
langjob_type2_c_predict<- (table(true = gi$langjob_d, pred = round(fitted(langjob_type2_c)))[1,1]+table(true =gi$langjob_d, pred = round(fitted(langjob_type2_c)))[2,2] ) /nobs(langjob_type2_c) *100 # 71,4 % correctly predicted values


# McFadden's Pseudo R-squared
langjob_type2_c_baseline <- update(langjob_type2_c, formula= langjob_d ~ 1)
langjob_type2_c_McFadden <- 1 - as.vector(logLik(langjob_type2_c)/logLik(langjob_type2_c_baseline))
langjob_type2_c_McFadden 


# #### 2 a4 type2 + c w/o education and w/education as consumption motive (uncomment if neccessary) ####
# table(giwo$type2)
# langjob_type2_c_wo<-glm(formula = langjob_full_type2_c, family = binomial(link = "probit"), data = giwo)
# langjob_type2_c_het_wo <- print(coeftest(langjob_type2_c_wo, vcovCL), digits=6)
# nobs(langjob_type2_c_wo)
# 
# 
# # Marginal effects (Average marginal effects)
# langjob_type2_c_ame_wo <- probitmfx(formula = langjob_full_type2_c,
#                                  data = giwo,
#                                  atmean = FALSE, 
#                                  robust = TRUE, 
#                                  clustervar1 = NULL, clustervar2 = NULL, 
#                                  start = NULL, control = list())
# # average marginal effects with heteroscedasticity-robust White standard errors
# print(langjob_type2_c_ame_wo)
# 
# 
# # Percent correctly predicted values
# langjob_type2_c_predict_wo<- (table(true = giwo$langjob_d, pred = round(fitted(langjob_type2_c_wo)))[1,1]+table(true =giwo$langjob_d, pred = round(fitted(langjob_type2_c_wo)))[2,2] ) /nobs(langjob_type2_c_wo) *100 # 71,4 % correctly predicted values
# 
# 
# # McFadden's Pseudo R-squared
# langjob_type2_c_baseline_wo <- update(langjob_type2_c_wo, formula= langjob_d ~ 1)
# langjob_type2_c_McFadden_wo <- 1 - as.vector(logLik(langjob_type2_c_wo)/logLik(langjob_type2_c_baseline_wo))
# langjob_type2_c_McFadden_wo 
# 
# 
#### 2 a4 Output ####
stargazer(langjob_fe_ame$fit,
          langjob_type_fe_ame$fit, 
          langjob_type2_fe_ame$fit,
          langjob_type2_c_ame$fit,
          coef = list(langjob_fe_ame$mfxest[,1], 
                      langjob_type_fe_ame$mfxest[,1], 
                      langjob_type2_fe_ame$mfxest[,1],
                      langjob_type2_c_ame$mfxest[,1]),
          se = list(langjob_fe_ame$mfxest[,2],
                   langjob_type_fe_ame$mfxest[,2],
                   langjob_type2_fe_ame$mfxest[,2],
                   langjob_type2_c_ame$mfxest[,2]),
          header=TRUE,
          p.auto=FALSE,
          style="default",
          nobs=TRUE,
          align=TRUE, 
          no.space=TRUE, 
          single.row=FALSE,
          model.names = FALSE,
          dep.var.labels   = "Professional use of German",
          covariate.labels= c(    "Investment",
                                  "Domestic labour market",
                                  "Educational and labour migration",
                                  "Personal reasons",
                                  "Cultural interest",
                                  "Age: under 35 years",
                                  "Gender: female",
                                  "Gender: n/a",
                                  "Children",
                                  "Partner (native German)",
                                  "Partner (other native)",
                                  "Occ.: high appl./low comm. skills",
                                  "Occ.: high appl./high comm. skills",
                                  "Occ.: in education",
                                  "Occ.: other occ./no answer",
                                  "University degree",
                                  "Risk attitude",
                                  "Patience",
                                  "English speaker",
                                  "Germanic lang.",
                                  "European (Non-EU)",
                                  "Non-European",
                                  "Upper-middle income",
                                  "High income",
                                  "Cultural distance: LTO",
                                  "Cultural distance: IVR"),
          omit = c("Constant", "country", "empstat4"),
          font.size = "small",
          add.lines = list(c("Country FE", "Yes", "Yes", "Yes", "No"),
                           c("McFadden Pseudo R2", round(langjob_fe_McFadden , digits=2), 
                             round(langjob_type_fe_McFadden , digits=2) ,
                             round(langjob_type2_fe_McFadden , digits=2),
                             round(langjob_type2_c_McFadden , digits=2)
                             ),
                           c("Percent. correctly predicted", round(langjob_fe_predict, digits=1) ,
                             round(langjob_type_fe_predict, digits=1) ,
                             round(langjob_type2_fe_predict, digits=1) ,
                             round(langjob_type2_c_predict, digits=1)
                             )),
          omit.stat = c("aic", "ll"),
          omit.table.layout = "n")


# #### 2 a5 Output w/o education and w/education as consumption motive (uncomment if neccessary) -----------
# stargazer(langjob_type_fe_ame_wo$fit, 
#           langjob_type2_c_ame_wo$fit,
#           langjob_type_fe_ame$fit, 
#           langjob_type2_c_ame$fit,
#           coef = list(langjob_type_fe_ame_wo$mfxest[,1], 
#                       langjob_type2_c_ame_wo$mfxest[,1],
#                       langjob_type_fe_ame$mfxest[,1], 
#                       langjob_type2_c_ame$mfxest[,1]),
#           se = list(langjob_type_fe_ame_wo$mfxest[,2],
#                     langjob_type2_c_ame_wo$mfxest[,2],
#                     langjob_type_fe_ame$mfxest[,2],
#                     langjob_type2_c_ame$mfxest[,2]),
#           header=TRUE,
#           p.auto=FALSE,
#           style="default",
#           nobs=TRUE,
#           align=TRUE, 
#           no.space=TRUE, 
#           single.row=FALSE,
#           model.names = FALSE,
#           dep.var.labels   = "Professional use of German",
#           covariate.labels= c(    "Investment",
#                                   "Age: under 35 years",
#                                   "Gender: female",
#                                   "Gender: n/a",
#                                   "Children",
#                                   "Partner (native German)",
#                                   "Partner (other native)",
#                                   "Occ.: high appl./low comm. skills",
#                                   "Occ.: high appl./high comm. skills",
#                                   "Occ.: in education",
#                                   "Occ.: other occ./no answer",
#                                   "University degree",
#                                   "Risk attitude",
#                                   "Patience",
#                                   "English speaker",
#                                   "Germanic lang.",
#                                   "Non-EU (European)",
#                                   "Non-EU (Non-European)",
#                                   "Upper-middle income",
#                                   "High income",
#                                   "Cultural distance: LTO",
#                                   "Cultural distance: IVR"),
#           omit = c("Constant", "country", "empstat4"),
#           font.size = "small",
#           add.lines = list(c("Country FE", "Yes", "No", "Yes", "No"),
#                            c("McFadden Pseudo R2", 
#                              round(langjob_type_fe_McFadden_wo, digits=2),
#                              round(langjob_type2_c_McFadden_wo, digits=2),
#                              round(langjob_type_fe_McFadden, digits=2),
#                              round(langjob_type2_c_McFadden, digits=2)
#                            ),
#                            c("Percent. correctly predicted", 
#                              round(langjob_type_fe_predict_wo, digits=1),
#                              round(langjob_type2_c_predict_wo, digits=1),
#                              round(langjob_type_fe_predict, digits=1),
#                              round(langjob_type2_c_predict, digits=1)
#                            )),
#           omit.stat = c("aic", "ll"),
#           omit.table.layout = "n")
# 
#### 2 b1a base langjob female ####
gi_female<-gi[gi$female==1,]


langjob_female_full_fe<-as.formula("langjob_d ~ factor(age)+children_d_na+part+occupationac+degree+risk+patient+english+country") #+mig_phase
langjob_female_full_type_fe<-as.formula("langjob_d ~ type + factor(age)+children_d_na+part+occupationac+degree+risk+patient+english+country") #+mig_phase
langjob_female_full_type2_fe<-as.formula("langjob_d ~ type2+factor(age)+children_d_na+part+occupationac+degree+risk+patient+english+country") #+mig_phase

langjob_female_fe<-glm(formula = langjob_female_full_fe, family = binomial(link = "probit"), data = gi_female)
langjob_female_fe_het <- print(coeftest(langjob_female_fe, vcovCL), digits=6)
nobs(langjob_female_fe)


# Marginal effects (Average marginal effects)
langjob_female_fe_ame <- probitmfx(formula = langjob_female_full_fe,
                            data=gi_female,
                            atmean = FALSE, 
                            robust = TRUE, 
                            clustervar1 = NULL, clustervar2 = NULL, 
                            start = NULL, control = list())
# average marginal effects with heteroscedasticity-robust White standard errors
print(langjob_female_fe_ame)


# Percent correctly predicted values
langjob_female_fe_predict<- (table(true = gi_female$langjob_d, pred = round(fitted(langjob_female_fe)))[1,1]+table(true = gi_female$langjob_d, pred = round(fitted(langjob_female_fe)))[2,2] ) /nobs(langjob_female_fe) *100 # 71,4 % correctly predicted values

# McFadden's Pseudo R-squared
langjob_female_fe_baseline <- update(langjob_female_fe, formula= langjob_d ~ 1)
langjob_female_fe_McFadden <- 1 - as.vector(logLik(langjob_female_fe)/logLik(langjob_female_fe_baseline))
langjob_female_fe_McFadden 




#### 2 b1b type female####

langjob_female_type_fe<-glm(formula = langjob_full_type_fe_g, family = binomial(link = "probit"), data = gi_female)
langjob_female_type_fe_het <- print(coeftest(langjob_female_type_fe, vcovCL), digits=6)
nobs(langjob_female_type_fe)


# Marginal effects (Average marginal effects)
langjob_female_type_fe_ame <- probitmfx(formula = langjob_female_full_type_fe,
                                 data=gi_female,
                                 atmean = FALSE, 
                                 robust = TRUE, 
                                 clustervar1 = NULL, clustervar2 = NULL, 
                                 start = NULL, control = list())
# average marginal effects with heteroscedasticity-robust White standard errors
print(langjob_female_type_fe_ame)


# Percent correctly predicted values
langjob_female_type_fe_predict<- (table(true = gi_female$langjob_d, pred = round(fitted(langjob_female_type_fe)))[1,1]+table(true = gi_female$langjob_d, pred = round(fitted(langjob_female_type_fe)))[2,2] ) /nobs(langjob_female_type_fe) *100# 71,4 % correctly predicted values


# McFadden's Pseudo R-squared
langjob_female_type_fe_baseline <- update(langjob_female_type_fe, formula= langjob_d ~ 1)
langjob_female_type_fe_McFadden <- 1 - as.vector(logLik(langjob_female_type_fe)/logLik(langjob_female_type_fe_baseline))
langjob_female_type_fe_McFadden 


#### 2 b1c type2 female ####
langjob_female_type2_fe<-glm(formula = langjob_female_full_type2_fe, family = binomial(link = "probit"), data = gi_female[gi_female$type2!="No answer",])
langjob_female_type2_fe_het <- print(coeftest(langjob_female_type2_fe, vcovCL), digits=6)
nobs(langjob_female_type2_fe)


# Marginal effects (Average marginal effects)
langjob_female_type2_fe_ame <- probitmfx(formula = langjob_female_full_type2_fe,
                                  data=gi_female[gi_female$type2!="No answer",],
                                  atmean = FALSE, 
                                  robust = TRUE, 
                                  clustervar1 = NULL, clustervar2 = NULL, 
                                  start = NULL, control = list())
# average marginal effects with heteroscedasticity-robust White standard errors
print(langjob_female_type2_fe_ame)


# Percent correctly predicted values
langjob_female_type2_fe_predict<- (table(true = gi_female[gi_female$type2!="No answer",]$langjob_d, pred = round(fitted(langjob_female_type2_fe)))[1,1]+table(true = gi_female[gi_female$type2!="No answer",]$langjob_d, pred = round(fitted(langjob_female_type2_fe)))[2,2] ) /nobs(langjob_female_type2_fe) *100 # 71,4 % correctly predicted values


# McFadden's Pseudo R-squared
langjob_female_type2_fe_baseline <- update(langjob_female_type2_fe, formula= langjob_d ~ 1)
langjob_female_type2_fe_McFadden <- 1 - as.vector(logLik(langjob_female_type2_fe)/logLik(langjob_female_type2_fe_baseline))
langjob_female_type2_fe_McFadden 


#
#### 2 b1d base langjob male ####
gi_male<-gi[gi$female==0,]


langjob_male_full_fe<-as.formula("langjob_d ~ factor(age)+children_d_na+part+occupationac+degree+risk+patient+english+country") #+mig_phase
langjob_male_full_type_fe<-as.formula("langjob_d ~ type + factor(age)+children_d_na+part+occupationac+degree+risk+patient+english+country") #+mig_phase
langjob_male_full_type2_fe<-as.formula("langjob_d ~ type2+factor(age)+children_d_na+part+occupationac+degree+risk+patient+english+country") #+mig_phase

langjob_male_fe<-glm(formula = langjob_male_full_fe, family = binomial(link = "probit"), data = gi_male)
langjob_male_fe_het <- print(coeftest(langjob_male_fe, vcovCL), digits=6)
nobs(langjob_male_fe)


# Marginal effects (Average marginal effects)
langjob_male_fe_ame <- probitmfx(formula = langjob_male_full_fe,
                                   data=gi_male,
                                   atmean = FALSE, 
                                   robust = TRUE, 
                                   clustervar1 = NULL, clustervar2 = NULL, 
                                   start = NULL, control = list())
# average marginal effects with heteroscedasticity-robust White standard errors
print(langjob_male_fe_ame)


# Percent correctly predicted values
langjob_male_fe_predict<- (table(true = gi_male$langjob_d, pred = round(fitted(langjob_male_fe)))[1,1]+table(true = gi_male$langjob_d, pred = round(fitted(langjob_male_fe)))[2,2] ) /nobs(langjob_male_fe) *100 # 71,4 % correctly predicted values

# McFadden's Pseudo R-squared
langjob_male_fe_baseline <- update(langjob_male_fe, formula= langjob_d ~ 1)
langjob_male_fe_McFadden <- 1 - as.vector(logLik(langjob_male_fe)/logLik(langjob_male_fe_baseline))
langjob_male_fe_McFadden 




#### 2 b1e type male####

langjob_male_type_fe<-glm(formula = langjob_full_type_fe_g, family = binomial(link = "probit"), data = gi_male)
langjob_male_type_fe_het <- print(coeftest(langjob_male_type_fe, vcovCL), digits=6)
nobs(langjob_male_type_fe)


# Marginal effects (Average marginal effects)
langjob_male_type_fe_ame <- probitmfx(formula = langjob_male_full_type_fe,
                                        data=gi_male,
                                        atmean = FALSE, 
                                        robust = TRUE, 
                                        clustervar1 = NULL, clustervar2 = NULL, 
                                        start = NULL, control = list())
# average marginal effects with heteroscedasticity-robust White standard errors
print(langjob_male_type_fe_ame)


# Percent correctly predicted values
langjob_male_type_fe_predict<- (table(true = gi_male$langjob_d, pred = round(fitted(langjob_male_type_fe)))[1,1]+table(true = gi_male$langjob_d, pred = round(fitted(langjob_male_type_fe)))[2,2] ) /nobs(langjob_male_type_fe) *100# 71,4 % correctly predicted values


# McFadden's Pseudo R-squared
langjob_male_type_fe_baseline <- update(langjob_male_type_fe, formula= langjob_d ~ 1)
langjob_male_type_fe_McFadden <- 1 - as.vector(logLik(langjob_male_type_fe)/logLik(langjob_male_type_fe_baseline))
langjob_male_type_fe_McFadden 


#### 2 b1f type2 male ####
langjob_male_type2_fe<-glm(formula = langjob_male_full_type2_fe, family = binomial(link = "probit"), data = gi_male[gi_male$type2!="No answer",])
langjob_male_type2_fe_het <- print(coeftest(langjob_male_type2_fe, vcovCL), digits=6)
nobs(langjob_male_type2_fe)


# Marginal effects (Average marginal effects)
langjob_male_type2_fe_ame <- probitmfx(formula = langjob_male_full_type2_fe,
                                         data=gi_male[gi_male$type2!="No answer",],
                                         atmean = FALSE, 
                                         robust = TRUE, 
                                         clustervar1 = NULL, clustervar2 = NULL, 
                                         start = NULL, control = list())
# average marginal effects with heteroscedasticity-robust White standard errors
print(langjob_male_type2_fe_ame)


# Percent correctly predicted values
langjob_male_type2_fe_predict<- (table(true = gi_male[gi_male$type2!="No answer",]$langjob_d, pred = round(fitted(langjob_male_type2_fe)))[1,1]+table(true = gi_male[gi_male$type2!="No answer",]$langjob_d, pred = round(fitted(langjob_male_type2_fe)))[2,2] ) /nobs(langjob_male_type2_fe) *100 # 71,4 % correctly predicted values


# McFadden's Pseudo R-squared
langjob_male_type2_fe_baseline <- update(langjob_male_type2_fe, formula= langjob_d ~ 1)
langjob_male_type2_fe_McFadden <- 1 - as.vector(logLik(langjob_male_type2_fe)/logLik(langjob_male_type2_fe_baseline))
langjob_male_type2_fe_McFadden 


#### 2 b1g type no uni deg####
gi_nodeg<-gi[gi$degree==FALSE,]
langjob_nodeg_full_fe<-as.formula("langjob_d ~ type + factor(age)+female+children_d_na+part+occupationac+risk+patient+english+country") #+mig_phase

langjob_nodeg_type_fe<-glm(formula = langjob_nodeg_full_fe, family = binomial(link = "probit"), data = gi_nodeg)
langjob_nodeg_type_fe_het <- print(coeftest(langjob_nodeg_type_fe, vcovCL), digits=6)
nobs(langjob_nodeg_type_fe)


# Marginal effects (Average marginal effects)
langjob_nodeg_type_fe_ame <- probitmfx(formula = langjob_nodeg_full_fe,
                                        data=gi_nodeg,
                                        atmean = FALSE, 
                                        robust = TRUE, 
                                        clustervar1 = NULL, clustervar2 = NULL, 
                                        start = NULL, control = list())
# average marginal effects with heteroscedasticity-robust White standard errors
print(langjob_nodeg_type_fe_ame)


# Percent correctly predicted values
langjob_nodeg_type_fe_predict<- (table(true = gi_nodeg$langjob_d, pred = round(fitted(langjob_nodeg_type_fe)))[1,1]+table(true = gi_nodeg$langjob_d, pred = round(fitted(langjob_nodeg_type_fe)))[2,2] ) /nobs(langjob_nodeg_type_fe) *100# 71,4 % correctly predicted values


# McFadden's Pseudo R-squared
langjob_nodeg_type_fe_baseline <- update(langjob_nodeg_type_fe, formula= langjob_d ~ 1)
langjob_nodeg_type_fe_McFadden <- 1 - as.vector(logLik(langjob_nodeg_type_fe)/logLik(langjob_nodeg_type_fe_baseline))
langjob_nodeg_type_fe_McFadden 


#### 2 b1g type uni deg####
gi_deg<-gi[gi$degree==TRUE,]
langjob_deg_full_fe<-as.formula("langjob_d ~ type + factor(age)+female+children_d_na+part+occupationac+risk+patient+english+country") #+mig_phase

langjob_deg_type_fe<-glm(formula = langjob_deg_full_fe, family = binomial(link = "probit"), data = gi_deg)
langjob_deg_type_fe_het <- print(coeftest(langjob_deg_type_fe, vcovCL), digits=6)
nobs(langjob_deg_type_fe)


# Marginal effects (Average marginal effects)
langjob_deg_type_fe_ame <- probitmfx(formula = langjob_deg_full_fe,
                                       data=gi_deg,
                                       atmean = FALSE, 
                                       robust = TRUE, 
                                       clustervar1 = NULL, clustervar2 = NULL, 
                                       start = NULL, control = list())
# average marginal effects with heteroscedasticity-robust White standard errors
print(langjob_deg_type_fe_ame)


# Percent correctly predicted values
langjob_deg_type_fe_predict<- (table(true = gi_deg$langjob_d, pred = round(fitted(langjob_deg_type_fe)))[1,1]+table(true = gi_deg$langjob_d, pred = round(fitted(langjob_deg_type_fe)))[2,2] ) /nobs(langjob_deg_type_fe) *100# 71,4 % correctly predicted values


# McFadden's Pseudo R-squared
langjob_deg_type_fe_baseline <- update(langjob_deg_type_fe, formula= langjob_d ~ 1)
langjob_deg_type_fe_McFadden <- 1 - as.vector(logLik(langjob_deg_type_fe)/logLik(langjob_deg_type_fe_baseline))
langjob_deg_type_fe_McFadden 


#### 2 b2a base langjob young ####
gi_young<-gi[gi$age==TRUE,]


langjob_young_full_fe<-as.formula("langjob_d ~ female+children_d_na+part+occupationac+degree+risk+patient+english+country") #+mig_phase
langjob_young_full_type_fe<-as.formula("langjob_d ~ type + female+children_d_na+part+occupationac+degree+risk+patient+english+country") #+mig_phase
langjob_young_full_type2_fe<-as.formula("langjob_d ~ type2+female++children_d_na+part+occupationac+degree+risk+patient+english+country") #+mig_phase

langjob_young_fe<-glm(formula = langjob_young_full_fe, family = binomial(link = "probit"), data = gi_young)
langjob_young_fe_het <- print(coeftest(langjob_young_fe, vcovCL), digits=6)
nobs(langjob_young_fe)


# Marginal effects (Average marginal effects)
langjob_young_fe_ame <- probitmfx(formula = langjob_young_full_fe,
                                   data=gi_young,
                                   atmean = FALSE, 
                                   robust = TRUE, 
                                   clustervar1 = NULL, clustervar2 = NULL, 
                                   start = NULL, control = list())
# average marginal effects with heteroscedasticity-robust White standard errors
print(langjob_young_fe_ame)


# Percent correctly predicted values
langjob_young_fe_predict<- (table(true = gi_young$langjob_d, pred = round(fitted(langjob_young_fe)))[1,1]+table(true = gi_young$langjob_d, pred = round(fitted(langjob_young_fe)))[2,2] ) /nobs(langjob_young_fe) *100 # 71,4 % correctly predicted values

# McFadden's Pseudo R-squared
langjob_young_fe_baseline <- update(langjob_young_fe, formula= langjob_d ~ 1)
langjob_young_fe_McFadden <- 1 - as.vector(logLik(langjob_young_fe)/logLik(langjob_young_fe_baseline))
langjob_young_fe_McFadden 




#### 2 b2b type young####

langjob_young_type_fe<-glm(formula = langjob_young_full_type_fe, family = binomial(link = "probit"), data = gi_young)
langjob_young_type_fe_het <- print(coeftest(langjob_young_type_fe, vcovCL), digits=6)
nobs(langjob_young_type_fe)


# Marginal effects (Average marginal effects)
langjob_young_type_fe_ame <- probitmfx(formula = langjob_young_full_type_fe,
                                        data=gi_young,
                                        atmean = FALSE, 
                                        robust = TRUE, 
                                        clustervar1 = NULL, clustervar2 = NULL, 
                                        start = NULL, control = list())
# average marginal effects with heteroscedasticity-robust White standard errors
print(langjob_young_type_fe_ame)


# Percent correctly predicted values
langjob_young_type_fe_predict<- (table(true = gi_young$langjob_d, pred = round(fitted(langjob_young_type_fe)))[1,1]+table(true = gi_young$langjob_d, pred = round(fitted(langjob_young_type_fe)))[2,2] ) /nobs(langjob_young_type_fe) *100# 71,4 % correctly predicted values


# McFadden's Pseudo R-squared
langjob_young_type_fe_baseline <- update(langjob_young_type_fe, formula= langjob_d ~ 1)
langjob_young_type_fe_McFadden <- 1 - as.vector(logLik(langjob_young_type_fe)/logLik(langjob_young_type_fe_baseline))
langjob_young_type_fe_McFadden 



#### 2 b2d base langjob old ####
gi_old<-gi[gi$age==FALSE,]


langjob_old_full_fe<-as.formula("langjob_d ~ female+children_d_na+part+occupationac+degree+risk+patient+english+country") #+mig_phase
langjob_old_full_type_fe<-as.formula("langjob_d ~ type + female+children_d_na+part+occupationac+degree+risk+patient+english+country") #+mig_phase
langjob_old_full_type2_fe<-as.formula("langjob_d ~ type2+female++children_d_na+part+occupationac+degree+risk+patient+english+country") #+mig_phase

langjob_old_fe<-glm(formula = langjob_old_full_fe, family = binomial(link = "probit"), data = gi_old)
langjob_old_fe_het <- print(coeftest(langjob_old_fe, vcovCL), digits=6)
nobs(langjob_old_fe)


# Marginal effects (Average marginal effects)
langjob_old_fe_ame <- probitmfx(formula = langjob_old_full_fe,
                                  data=gi_old,
                                  atmean = FALSE, 
                                  robust = TRUE, 
                                  clustervar1 = NULL, clustervar2 = NULL, 
                                  start = NULL, control = list())
# average marginal effects with heteroscedasticity-robust White standard errors
print(langjob_old_fe_ame)


# Percent correctly predicted values
langjob_old_fe_predict<- (table(true = gi_old$langjob_d, pred = round(fitted(langjob_old_fe)))[1,1]+table(true = gi_old$langjob_d, pred = round(fitted(langjob_old_fe)))[2,2] ) /nobs(langjob_old_fe) *100 # 71,4 % correctly predicted values

# McFadden's Pseudo R-squared
langjob_old_fe_baseline <- update(langjob_old_fe, formula= langjob_d ~ 1)
langjob_old_fe_McFadden <- 1 - as.vector(logLik(langjob_old_fe)/logLik(langjob_old_fe_baseline))
langjob_old_fe_McFadden 




#### 2 b2e type old####

langjob_old_type_fe<-glm(formula = langjob_old_full_type_fe, family = binomial(link = "probit"), data = gi_old)
langjob_old_type_fe_het <- print(coeftest(langjob_old_type_fe, vcovCL), digits=6)
nobs(langjob_old_type_fe)


# Marginal effects (Average marginal effects)
langjob_old_type_fe_ame <- probitmfx(formula = langjob_old_full_type_fe,
                                       data=gi_old,
                                       atmean = FALSE, 
                                       robust = TRUE, 
                                       clustervar1 = NULL, clustervar2 = NULL, 
                                       start = NULL, control = list())
# average marginal effects with heteroscedasticity-robust White standard errors
print(langjob_old_type_fe_ame)


# Percent correctly predicted values
langjob_old_type_fe_predict<- (table(true = gi_old$langjob_d, pred = round(fitted(langjob_old_type_fe)))[1,1]+table(true = gi_old$langjob_d, pred = round(fitted(langjob_old_type_fe)))[2,2] ) /nobs(langjob_old_type_fe) *100# 71,4 % correctly predicted values


# McFadden's Pseudo R-squared
langjob_old_type_fe_baseline <- update(langjob_old_type_fe, formula= langjob_d ~ 1)
langjob_old_type_fe_McFadden <- 1 - as.vector(logLik(langjob_old_type_fe)/logLik(langjob_old_type_fe_baseline))
langjob_old_type_fe_McFadden 


#### 2 b4 Output subsamples age gender ####

stargazer(langjob_female_type_fe_ame$fit,
          langjob_male_type_fe_ame$fit,
          langjob_young_type_fe_ame$fit,
          langjob_old_type_fe_ame$fit,
          langjob_deg_type_fe_ame$fit,
          langjob_nodeg_type_fe_ame$fit,
          coef = list(langjob_female_type_fe_ame$mfxest[,1],
                      langjob_male_type_fe_ame$mfxest[,1],
                      langjob_young_type_fe_ame$mfxest[,1],
                      langjob_old_type_fe_ame$mfxest[,1],
                      langjob_nodeg_type_fe_ame$mfxest[,1],
                      langjob_deg_type_fe_ame$mfxest[,1]
                      ),
          se = list(langjob_female_type_fe_ame$mfxest[,2],
                    langjob_male_type_fe_ame$mfxest[,2],
                    langjob_young_type_fe_ame$mfxest[,2],
                    langjob_old_type_fe_ame$mfxest[,2],
                    langjob_nodeg_type_fe_ame$mfxest[,2],
                    langjob_deg_type_fe_ame$mfxest[,2]
                    ),
          header=TRUE,
          p.auto=FALSE,
          style="default",
          nobs=TRUE,
          align=TRUE, 
          no.space=TRUE, 
          single.row=FALSE,
          model.names = FALSE,
          dep.var.labels   = "Professional use of German",
          column.labels = c("female", "male","age: <35", "age: >=35", "no uni. deg.", "uni. deg." ),
          covariate.labels= c(       "Investment",
                                  "Age: under 35 years",
                                  "Gender: female",
                                  "Gender: n/a",
                                  "Children",
                                  "Partner (native German)",
                                  "Partner (other native)",
                                  "Occ.: high appl./low comm. skills",
                                  "Occ.: high appl./high comm. skills",
                                  "Occ.: in education",
                                  "Occ.: other occ./no answer",
                                  "University degree",
                                  "Risk attitude",
                                  "Patience",
                                  "English speaker"),
          omit = c("Constant", "country", "empstat4"),
          font.size = "small",
          add.lines = list(c("Country FE", "Yes", "Yes", "Yes", "Yes", "Yes", "Yes", "Yes"),
                           c("McFadden Pseudo R2",
                             round(langjob_female_type_fe_McFadden , digits=2) ,
                             round(langjob_male_type_fe_McFadden , digits=2) ,
                             round(langjob_young_type_fe_McFadden , digits=2) ,
                             round(langjob_old_type_fe_McFadden , digits=2),
                             round(langjob_nodeg_type_fe_McFadden , digits=2),
                             round(langjob_deg_type_fe_McFadden , digits=2)),
                           c("% correctly predicted",
                             round(langjob_female_type_fe_predict, digits=1) ,
                             round(langjob_male_type_fe_predict, digits=1),
                             round(langjob_young_type_fe_predict, digits=1) ,
                             round(langjob_old_type_fe_predict, digits=1),
                             round(langjob_nodeg_type_fe_predict, digits=1) ,
                             round(langjob_deg_type_fe_predict, digits=1))),
          omit.stat = c("aic", "ll"),
          omit.table.layout = "n")


#### 2 b3 langjobsubsamble ####

#### 2 b3a langjob inv ####


gi_inv<-gi[gi$type==TRUE,]


langjob_full_coninv_type2_fe<-as.formula("langjob_d ~ type2+factor(age)+female+children_d_na+part+occupationac+degree+risk+patient+english+country") #+mig_phase



langjob_inv_type2_fe<-glm(formula = langjob_full_coninv_type2_fe, family = binomial(link = "probit"), data = gi_inv[gi_inv$type2!="No answer",])
langjob_inv_type2_fe_het <- print(coeftest(langjob_inv_type2_fe, vcovCL), digits=6)
nobs(langjob_inv_type2_fe)


# Marginal effects (Average marginal effects)
langjob_inv_type2_fe_ame <- probitmfx(formula = langjob_full_coninv_type2_fe,
                                      data=gi_inv[gi_inv$type2!="No answer",],
                                      atmean = FALSE, 
                                      robust = TRUE, 
                                      clustervar1 = NULL, clustervar2 = NULL, 
                                      start = NULL, control = list())
# average marginal effects with heteroscedasticity-robust White standard errors
print(langjob_inv_type2_fe_ame)


# Percent correctly predicted values
langjob_inv_type2_fe_predict<- (table(true = gi_inv[gi_inv$type2!="No answer",]$langjob_d, pred = round(fitted(langjob_inv_type2_fe)))[1,1]+table(true = gi_inv[gi_inv$type2!="No answer",]$langjob_d, pred = round(fitted(langjob_inv_type2_fe)))[2,2] ) /nobs(langjob_inv_type2_fe) *100 # 71,4 % correctly predicted values


# McFadden's Pseudo R-squared
langjob_inv_type2_fe_baseline <- update(langjob_inv_type2_fe, formula= langjob_d ~ 1)
langjob_inv_type2_fe_McFadden <- 1 - as.vector(logLik(langjob_inv_type2_fe)/logLik(langjob_inv_type2_fe_baseline))
langjob_inv_type2_fe_McFadden 


#### 2 b3b langjob con ####


gi_con<-gi[gi$type==FALSE,]


langjob_full_coninv_type2_fe<-as.formula("langjob_d ~ type2+factor(age)+female+children_d_na+part+occupationac+degree+risk+patient+english+country") #+mig_phase



langjob_con_type2_fe<-glm(formula = langjob_full_coninv_type2_fe, family = binomial(link = "probit"), data = gi_con[gi_con$type2!="No answer",])
langjob_con_type2_fe_het <- print(coeftest(langjob_con_type2_fe, vcovCL), digits=6)
nobs(langjob_con_type2_fe)


# Marginal effects (Average marginal effects)
langjob_con_type2_fe_ame <- probitmfx(formula = langjob_full_coninv_type2_fe,
                                      data=gi_con[gi_con$type2!="No answer",],
                                      atmean = FALSE, 
                                      robust = TRUE, 
                                      clustervar1 = NULL, clustervar2 = NULL, 
                                      start = NULL, control = list())
# average marginal effects with heteroscedasticity-robust White standard errors
print(langjob_con_type2_fe_ame)


# Percent correctly predicted values
langjob_con_type2_fe_predict<- (table(true = gi_con[gi_con$type2!="No answer",]$langjob_d, pred = round(fitted(langjob_con_type2_fe)))[1,1]+table(true = gi_con[gi_con$type2!="No answer",]$langjob_d, pred = round(fitted(langjob_con_type2_fe)))[2,2] ) /nobs(langjob_con_type2_fe) *100 # 71,4 % correctly predicted values


# McFadden's Pseudo R-squared
langjob_con_type2_fe_baseline <- update(langjob_con_type2_fe, formula= langjob_d ~ 1)
langjob_con_type2_fe_McFadden <- 1 - as.vector(logLik(langjob_con_type2_fe)/logLik(langjob_con_type2_fe_baseline))
langjob_con_type2_fe_McFadden 




#### 2 b3c langjob inv ####


gi_inv<-gi[gi$type==TRUE,]


langjob_full_coninv_type_fe<-as.formula("langjob_d ~ factor(age)+female+children_d_na+part+occupationac+degree+risk+patient+english+country") #+mig_phase



langjob_inv_type_fe<-glm(formula = langjob_full_coninv_type_fe, family = binomial(link = "probit"), data = gi_inv)
langjob_inv_type_fe_het <- print(coeftest(langjob_inv_type_fe, vcovCL), digits=6)
nobs(langjob_inv_type_fe)


# Marginal effects (Average marginal effects)
langjob_inv_type_fe_ame <- probitmfx(formula = langjob_full_coninv_type_fe,
                                     data=gi_inv,
                                     atmean = FALSE, 
                                     robust = TRUE, 
                                     clustervar1 = NULL, clustervar2 = NULL, 
                                     start = NULL, control = list())
# average marginal effects with heteroscedasticity-robust White standard errors
print(langjob_inv_type_fe_ame)


# Percent correctly predicted values
langjob_inv_type_fe_predict<- (table(true = gi_inv$langjob_d, pred = round(fitted(langjob_inv_type_fe)))[1,1]+table(true = gi_inv$langjob_d, pred = round(fitted(langjob_inv_type_fe)))[2,2] ) /nobs(langjob_inv_type_fe) *100 # 71,4 % correctly predicted values


# McFadden's Pseudo R-squared
langjob_inv_type_fe_baseline <- update(langjob_inv_type_fe, formula= langjob_d ~ 1)
langjob_inv_type_fe_McFadden <- 1 - as.vector(logLik(langjob_inv_type_fe)/logLik(langjob_inv_type_fe_baseline))
langjob_inv_type_fe_McFadden 


#### 2 b3d langjob con ####


gi_con<-gi[gi$type==FALSE,]


langjob_full_coninv_type_fe<-as.formula("langjob_d ~ factor(age)+female+children_d_na+part+occupationac+degree+risk+patient+english+country") #+mig_phase



langjob_con_type_fe<-glm(formula = langjob_full_coninv_type_fe, family = binomial(link = "probit"), data = gi_con)
langjob_con_type_fe_het <- print(coeftest(langjob_con_type_fe, vcovCL), digits=6)
nobs(langjob_con_type_fe)


# Marginal effects (Average marginal effects)
langjob_con_type_fe_ame <- probitmfx(formula = langjob_full_coninv_type_fe,
                                     data=gi_con,
                                     atmean = FALSE, 
                                     robust = TRUE, 
                                     clustervar1 = NULL, clustervar2 = NULL, 
                                     start = NULL, control = list())
# average marginal effects with heteroscedasticity-robust White standard errors
print(langjob_con_type_fe_ame)


# Percent correctly predicted values
langjob_con_type_fe_predict<- (table(true = gi_con$langjob_d, pred = round(fitted(langjob_con_type_fe)))[1,1]+table(true = gi_con$langjob_d, pred = round(fitted(langjob_con_type_fe)))[2,2] ) /nobs(langjob_con_type_fe) *100 # 71,4 % correctly predicted values


# McFadden's Pseudo R-squared
langjob_con_type_fe_baseline <- update(langjob_con_type_fe, formula= langjob_d ~ 1)
langjob_con_type_fe_McFadden <- 1 - as.vector(logLik(langjob_con_type_fe)/logLik(langjob_con_type_fe_baseline))
langjob_con_type_fe_McFadden 



#### 2 b4 langjobsubsamble +reason_om ####

#### 2 b3a langjob inv ####


gi_inv<-gi[gi$type==TRUE,]


langjob_full_coninv_type2_fe<-as.formula("langjob_d ~ type2+factor(age)+female+children_d_na+part+occupationac+degree+risk+patient+english+reason_om+country") #+mig_phase



langjob_inv_type2_fe2<-glm(formula = langjob_full_coninv_type2_fe, family = binomial(link = "probit"), data = gi_inv[gi_inv$type2!="No answer",])
langjob_inv_type2_fe2_het <- print(coeftest(langjob_inv_type2_fe2, vcovCL), digits=6)
nobs(langjob_inv_type2_fe2)


# Marginal effects (Average marginal effects)
langjob_inv_type2_fe2_ame <- probitmfx(formula = langjob_full_coninv_type2_fe,
                                      data=gi_inv[gi_inv$type2!="No answer",],
                                      atmean = FALSE, 
                                      robust = TRUE, 
                                      clustervar1 = NULL, clustervar2 = NULL, 
                                      start = NULL, control = list())
# average marginal effects with heteroscedasticity-robust White standard errors
print(langjob_inv_type2_fe2_ame)


# Percent correctly predicted values
langjob_inv_type2_fe2_predict<- (table(true = gi_inv[gi_inv$type2!="No answer",]$langjob_d, pred = round(fitted(langjob_inv_type2_fe2)))[1,1]+table(true = gi_inv[gi_inv$type2!="No answer",]$langjob_d, pred = round(fitted(langjob_inv_type2_fe2)))[2,2] ) /nobs(langjob_inv_type2_fe2) *100 # 71,4 % correctly predicted values


# McFadden's Pseudo R-squared
langjob_inv_type2_fe2_baseline <- update(langjob_inv_type2_fe2, formula= langjob_d ~ 1)
langjob_inv_type2_fe2_McFadden <- 1 - as.vector(logLik(langjob_inv_type2_fe2)/logLik(langjob_inv_type2_fe2_baseline))
langjob_inv_type2_fe2_McFadden 


#### 2 b3b langjob con ####


gi_con<-gi[gi$type==FALSE,]


langjob_full_coninv_type2_fe2<-as.formula("langjob_d ~ type2+factor(age)+female+children_d_na+part+occupationac+degree+risk+patient+english+reason_om+country") #+mig_phase



langjob_con_type2_fe2<-glm(formula = langjob_full_coninv_type2_fe, family = binomial(link = "probit"), data = gi_con[gi_con$type2!="No answer",])
langjob_con_type2_fe2_het <- print(coeftest(langjob_con_type2_fe2, vcovCL), digits=6)
nobs(langjob_con_type2_fe2)


# Marginal effects (Average marginal effects)
langjob_con_type2_fe2_ame <- probitmfx(formula = langjob_full_coninv_type2_fe,
                                      data=gi_con[gi_con$type2!="No answer",],
                                      atmean = FALSE, 
                                      robust = TRUE, 
                                      clustervar1 = NULL, clustervar2 = NULL, 
                                      start = NULL, control = list())
# average marginal effects with heteroscedasticity-robust White standard errors
print(langjob_con_type2_fe2_ame)


# Percent correctly predicted values
langjob_con_type2_fe2_predict<- (table(true = gi_con[gi_con$type2!="No answer",]$langjob_d, pred = round(fitted(langjob_con_type2_fe2)))[1,1]+table(true = gi_con[gi_con$type2!="No answer",]$langjob_d, pred = round(fitted(langjob_con_type2_fe2)))[2,2] ) /nobs(langjob_con_type2_fe2) *100 # 71,4 % correctly predicted values


# McFadden's Pseudo R-squared
langjob_con_type2_fe2_baseline <- update(langjob_con_type2_fe2, formula= langjob_d ~ 1)
langjob_con_type2_fe2_McFadden <- 1 - as.vector(logLik(langjob_con_type2_fe2)/logLik(langjob_con_type2_fe2_baseline))
langjob_con_type2_fe2_McFadden 




#### 2 b3c langjob inv ####


gi_inv<-gi[gi$type==TRUE,]


langjob_full_coninv_type_fe<-as.formula("langjob_d ~ factor(age)+female+children_d_na+part+occupationac+degree+risk+patient+english+reason_om+country") #+mig_phase



langjob_inv_type_fe2<-glm(formula = langjob_full_coninv_type_fe, family = binomial(link = "probit"), data = gi_inv)
langjob_inv_type_fe2_het <- print(coeftest(langjob_inv_type_fe2, vcovCL), digits=6)
nobs(langjob_inv_type_fe2)


# Marginal effects (Average marginal effects)
langjob_inv_type_fe2_ame <- probitmfx(formula = langjob_full_coninv_type_fe,
                                     data=gi_inv,
                                     atmean = FALSE, 
                                     robust = TRUE, 
                                     clustervar1 = NULL, clustervar2 = NULL, 
                                     start = NULL, control = list())
# average marginal effects with heteroscedasticity-robust White standard errors
print(langjob_inv_type_fe2_ame)


# Percent correctly predicted values
langjob_inv_type_fe2_predict<- (table(true = gi_inv$langjob_d, pred = round(fitted(langjob_inv_type_fe2)))[1,1]+table(true = gi_inv$langjob_d, pred = round(fitted(langjob_inv_type_fe2)))[2,2] ) /nobs(langjob_inv_type_fe2) *100 # 71,4 % correctly predicted values


# McFadden's Pseudo R-squared
langjob_inv_type_fe2_baseline <- update(langjob_inv_type_fe2, formula= langjob_d ~ 1)
langjob_inv_type_fe2_McFadden <- 1 - as.vector(logLik(langjob_inv_type_fe2)/logLik(langjob_inv_type_fe2_baseline))
langjob_inv_type_fe2_McFadden 


#### 2 b3d langjob con ####


gi_con<-gi[gi$type==FALSE,]


langjob_full_coninv_type_fe<-as.formula("langjob_d ~ factor(age)+female+children_d_na+part+occupationac+degree+risk+patient+english+reason_om+country") #+mig_phase



langjob_con_type_fe2<-glm(formula = langjob_full_coninv_type_fe, family = binomial(link = "probit"), data = gi_con)
langjob_con_type_fe2_het <- print(coeftest(langjob_con_type_fe2, vcovCL), digits=6)
nobs(langjob_con_type_fe2)


# Marginal effects (Average marginal effects)
langjob_con_type_fe2_ame <- probitmfx(formula = langjob_full_coninv_type_fe,
                                     data=gi_con,
                                     atmean = FALSE, 
                                     robust = TRUE, 
                                     clustervar1 = NULL, clustervar2 = NULL, 
                                     start = NULL, control = list())
# average marginal effects with heteroscedasticity-robust White standard errors
print(langjob_con_type_fe2_ame)


# Percent correctly predicted values
langjob_con_type_fe2_predict<- (table(true = gi_con$langjob_d, pred = round(fitted(langjob_con_type_fe2)))[1,1]+table(true = gi_con$langjob_d, pred = round(fitted(langjob_con_type_fe2)))[2,2] ) /nobs(langjob_con_type_fe2) *100 # 71,4 % correctly predicted values


# McFadden's Pseudo R-squared
langjob_con_type_fe2_baseline <- update(langjob_con_type_fe2, formula= langjob_d ~ 1)
langjob_con_type_fe2_McFadden <- 1 - as.vector(logLik(langjob_con_type_fe2)/logLik(langjob_con_type_fe2_baseline))
langjob_con_type_fe2_McFadden 


#### Output ------
stargazer( langjob_con_type_fe_ame$fit, 
           langjob_inv_type_fe_ame$fit, 
           langjob_con_type_fe2_ame$fit, 
           langjob_inv_type_fe2_ame$fit, 
           coef = list(langjob_con_type_fe_ame$mfxest[,1], 
                       langjob_inv_type_fe_ame$mfxest[,1],
                       langjob_con_type_fe2_ame$mfxest[,1], 
                       langjob_inv_type_fe2_ame$mfxest[,1]),
           se = list(langjob_con_type_fe_ame$mfxest[,2], 
                     langjob_inv_type_fe_ame$mfxest[,2],
                     langjob_con_type_fe2_ame$mfxest[,2], 
                     langjob_inv_type_fe2_ame$mfxest[,2]),
           dep.var.labels   = "Professional use of German",
           column.labels = c("consumpt. good", "hum. cap. invest.", "consumpt. good", "hum. cap. invest."),
           covariate.labels= c( "Age: under 35 years",
                                "Gender: female",
                                "Gender: n/a",
                                "Children",
                                "Partner (native German)",
                                "Partner (other native)",
                                "Occ.: high appl./low comm. skills",
                                "Occ.: high appl./high comm. skills",
                                "Occ.: in education",
                                "Occ.: other occ./no answer",
                                "University degree",
                                "Risk attitude",
                                "Patience",
                                "English speaker",
                                "Other investm. reason"),
           header=TRUE,
           p.auto=FALSE,
           style="default",
           nobs=TRUE,
           align=TRUE, 
           no.space=TRUE, 
           single.row=FALSE,
           model.names = FALSE,
           omit = c("Constant", "country", "empstat4"),
           font.size = "small",
           add.lines = list(c("Country FE", "Yes", "Yes", "Yes", "Yes" ),
                            c("McFadden Pseudo R2", round(langjob_inv_type_fe_McFadden , digits=2) ,
                              round(langjob_con_type_fe_McFadden , digits=2) ,  
                              round(langjob_inv_type_fe2_McFadden , digits=2) ,
                              round(langjob_con_type_fe2_McFadden , digits=2) ),
                            c("% correctly predicted",  round(langjob_inv_type_fe_predict , digits=1) ,
                              round(langjob_con_type_fe_predict , digits=1),
                              round(langjob_inv_type_fe2_predict , digits=1) ,
                              round(langjob_con_type_fe2_predict , digits=1))),
           omit.stat = c("aic", "ll"),
           omit.table.layout = "n")


#### 2 c Country-wise ####


#### 2 c1 Countries ####

TOT<-probitmfx(formula = langjob_full_type2_fe, data=gi, atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
BIH<-probitmfx(formula = langjob_full_type2, data=gi[gi$country=="BIH",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
CZE<-probitmfx(formula = langjob_full_type2, data=gi[gi$country=="CZE",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
ESP<-probitmfx(formula = langjob_full_type2, data=gi[gi$country=="ESP",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
GBR<-probitmfx(formula = langjob_full_type2, data=gi[gi$country=="GBR",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
ITA<-probitmfx(formula = langjob_full_type2, data=gi[gi$country=="ITA",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
JPN<-probitmfx(formula = langjob_full_type2, data=gi[gi$country=="JPN",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
KOR<-probitmfx(formula = langjob_full_type2, data=gi[gi$country=="KOR",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
NLD<-probitmfx(formula = langjob_full_type2, data=gi[gi$country=="NLD",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
POL<-probitmfx(formula = langjob_full_type2, data=gi[gi$country=="POL",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
ROU<-probitmfx(formula = langjob_full_type2, data=gi[gi$country=="ROU",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
IND<-probitmfx(formula = langjob_full_type2, data=gi[gi$country=="IND",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
IDN<-probitmfx(formula = langjob_full_type2, data=gi[gi$country=="IDN",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
UKR<-probitmfx(formula = langjob_full_type2, data=gi[gi$country=="UKR",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
MEX<-probitmfx(formula = langjob_full_type2, data=gi[gi$country=="MEX",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())


stargazer(TOT$fit, 
          BIH$fit,
          CZE$fit, 
          ESP$fit,
          GBR$fit, 
          ITA$fit,
          JPN$fit, 
          KOR$fit,
          NLD$fit, 
          POL$fit,
          ROU$fit, 
          IND$fit,
          IDN$fit, 
          UKR$fit,
          MEX$fit, 
          coef = list(TOT$mfxest[,1], 
                      BIH$mfxest[,1],
                      CZE$mfxest[,1], 
                      ESP$mfxest[,1],
                      GBR$mfxest[,1], 
                      ITA$mfxest[,1],
                      JPN$mfxest[,1], 
                      KOR$mfxest[,1],
                      NLD$mfxest[,1], 
                      POL$mfxest[,1],
                      ROU$mfxest[,1], 
                      IND$mfxest[,1],
                      IDN$mfxest[,1], 
                      UKR$mfxest[,1],
                      MEX$mfxest[,1]),
          se = list(TOT$mfxest[,2],
                    BIH$mfxest[,2],
                    CZE$mfxest[,2],
                    ESP$mfxest[,2],
                    GBR$mfxest[,2],
                    ITA$mfxest[,2],
                    JPN$mfxest[,2],
                    KOR$mfxest[,2],
                    NLD$mfxest[,2],
                    POL$mfxest[,2],
                    ROU$mfxest[,2],
                    IND$mfxest[,2],
                    IDN$mfxest[,2],
                    UKR$mfxest[,2],
                    MEX$mfxest[,2]),
          column.labels = c("TOT", "BIH", "CZE", "ESP",  "GBR", "ITA", "JPN", "KOR", "NLD", "POL", "ROU", "IND", "IDN", "UKR", "MEX"),
          header=FALSE,
          style="default",
          dep.var.labels   = "Professional use of German",
          covariate.labels= c(    "Domestic labour market",
                                  "Educational and labour migration",
                                  "Personal reasons",
                                  "Cultural interest",
                                  "Age: under 35 years",
                                  "Gender: female",
                                  "Gender: n/a",
                                  "Children",
                                  "Partner (native German)",
                                  "Partner (other native)",
                                  "Occ.: in education",
                                  "Other occ./no answer",
                                  "University degree",
                                  "Risk attitude",
                                  "Patience",
                                  "Intern. applic. of education"
          ),
          nobs=TRUE,
          align=TRUE, 
          no.space=TRUE, 
          single.row=TRUE,
          model.names = FALSE,
          omit = c("Constant", "country", "empstat4"),
          font.size = "small",
          add.lines = list(c("Country FE", "Yes", "No", "No","No","No","No","No","No","No","No","No","No","No","No","No")),
          notes= "Average marginal effects. Heteroscedasticity robust White standard errors in parentheses.",
          omit.stat = c("aic", "ll"))


TOT_type<-tidy(TOT)  %>% filter(term != "(Intercept)") %>% mutate(model = "Total")
BIH_type<-tidy(BIH)  %>% filter(term != "(Intercept)") %>% mutate(model = "BIH (n=126)")
CZE_type<-tidy(CZE)  %>% filter(term != "(Intercept)") %>% mutate(model = "CZE (n=311)")
ESP_type<-tidy(ESP)  %>% filter(term != "(Intercept)") %>% mutate(model = "ESP (n=467)")
GBR_type<-tidy(GBR)  %>% filter(term != "(Intercept)") %>% mutate(model = "GBR (n=339)")
ITA_type<-tidy(ITA)  %>% filter(term != "(Intercept)") %>% mutate(model = "ITA (n=218)")
JPN_type<-tidy(JPN)  %>% filter(term != "(Intercept)") %>% mutate(model = "JPN (n=196)")
KOR_type<-tidy(KOR)  %>% filter(term != "(Intercept)") %>% mutate(model = "KOR (n=215)")
NLD_type<-tidy(NLD)  %>% filter(term != "(Intercept)") %>% mutate(model = "NLD (n=68)")
POL_type<-tidy(POL)  %>% filter(term != "(Intercept)") %>% mutate(model = "POL (n=138)")
ROU_type<-tidy(ROU)  %>% filter(term != "(Intercept)") %>% mutate(model = "ROU (n=223)")
IND_type<-tidy(IND)  %>% filter(term != "(Intercept)") %>% mutate(model = "IND (n=406)")
IDN_type<-tidy(IDN)  %>% filter(term != "(Intercept)") %>% mutate(model = "IDN (n=539)")
UKR_type<-tidy(UKR)  %>% filter(term != "(Intercept)") %>% mutate(model = "UKR (n=512)")
MEX_type<-tidy(MEX)  %>% filter(term != "(Intercept)") %>% mutate(model = "MEX (n=316)")



gi %>% count(country) %>% arrange(-n)

country_l_type<-rbind(TOT_type, 
                      ESP_type, GBR_type, CZE_type, ITA_type, POL_type, ROU_type, NLD_type,
                      BIH_type,  UKR_type, 
                      MEX_type, IND_type, IDN_type,
                      KOR_type, JPN_type)

country_l_type<-country_l_type %>% mutate(sign=ifelse(model=="Total" & p.value<0.05, TRUE, FALSE)) %>% 
  group_by(term) %>% mutate(sign_5=max(sign), sign=ifelse(sign_5==0, "P>0.05 (aggr. model)", "P<0.05 (aggr. model)"), sign=as.factor(sign)) %>% filter(model!="Total")


library(dotwhisker)
library(ggsci)


#### 2 c2a2 Country groups ####

gi<-gi[gi$type2!="No answer",]


eu_sw<-probitmfx(formula = langjob_full_type2_fe, data=gi[gi$country=="ESP" | gi$country=="ITA"| gi$country=="GBR" | gi$country=="NLD" ,],
                 atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
                 start = NULL, control = list())

eu_e<-probitmfx(formula = langjob_full_type2_fe, data=gi[gi$country=="CZE" | gi$country=="POL" | gi$country=="ROU",],
                atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
                start = NULL, control = list())

eur<- probitmfx(formula = langjob_full_type2_fe, data=gi[gi$country=="UKR" | gi$country=="BIH",], 
                atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
                start = NULL, control = list())

noneu_d<-probitmfx(formula = langjob_full_type2_fe, data=gi[gi$country=="JPN" | gi$country=="KOR",],
                   atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL,
                   start = NULL, control = list())

noneu_ld<-probitmfx(formula = langjob_full_type2_fe, data=gi[gi$country=="IDN" | gi$country=="IND" | gi$country=="MEX",], 
                    atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
                    start = NULL, control = list())

eu<-probitmfx(formula = langjob_full_type2_fe, data=gi[gi$country=="ESP" | gi$country=="ITA"|gi$country=="NLD" | gi$country=="GBR"|gi$country=="CZE" | gi$country=="POL" | gi$country=="ROU",], 
              atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
              start = NULL, control = list())

noneu<- probitmfx(formula = langjob_full_type2_fe, data=gi[gi$country=="MEX" | gi$country=="IDN" | gi$country=="IND"|gi$country=="JPN" | gi$country=="KOR"|gi$country=="UKR" | gi$country=="BIH",], 
                  atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
                  start = NULL, control = list())


stargazer(eu_sw$fit, 
          eu_e$fit,
          eur$fit, 
          noneu_d$fit,
          noneu_ld$fit, 
          eu$fit,
          noneu$fit, 
          coef = list(eu_sw$mfxest[,1], 
                      eu_e$mfxest[,1],
                      eur$mfxest[,1], 
                      noneu_d$mfxest[,1],
                      noneu_ld$mfxest[,1], 
                      eu$mfxest[,1],
                      noneu$mfxest[,1]),
          se = list(eu_sw$mfxest[,2], 
                    eu_e$mfxest[,2],
                    eur$mfxest[,2], 
                    noneu_d$mfxest[,2],
                    noneu_ld$mfxest[,2], 
                    eu$mfxest[,2],
                    noneu$mfxest[,2]),
          column.labels = c("ESP, ITA, GBR, NLD", "CZE, POL, ROU", "UKR, BIH",  "JPN, KOR", "IND, IDN, MEX", "EU", "Non-EU"),
          header=FALSE,
          style="default",
          dep.var.labels   = "Professional use of German",
          covariate.labels= c(    "Domestic labour market",
                                  "Educ. and labour migration",
                                  "Personal reasons",
                                  "Cultural interest",
                                  "Age: under 35 years",
                                  "Gender: female",
                                  "Gender: n/a",
                                  "Children",
                                  "Partner (native German)",
                                  "Partner (other native)",
                                  "Occ.: in education",
                                  "Other occ./no answer",
                                  "University degree",
                                  "Risk attitude",
                                  "Patience",
                                  "Intern. applic. of education"
          ),
          nobs=TRUE,
          align=FALSE, 
          no.space=TRUE, 
          single.row=FALSE,
          model.names = FALSE,
          omit = c("Constant", "country", "empstat4"),
          font.size = "small",
          add.lines = list(c("Country FE", "Yes", "Yes","Yes","Yes","Yes","Yes","Yes")),
          omit.stat = c("aic", "ll"),
          omit.table.layout = "n")

eu_sw_type<-tidy(eu_sw)  %>% filter(term != "(Intercept)") %>%  mutate(model = "ESP, ITA, GBR, NLD (n=1092)")
nrow(gi[gi$country=="ESP" | gi$country=="ITA"| gi$country=="GBR" | gi$country=="NLD" ,])

eu_e_type<-tidy(eu_e)  %>% filter(term != "(Intercept)") %>% mutate(model = "CZE, POL, ROU (n=682)")
nrow(gi[gi$country=="CZE" | gi$country=="POL" | gi$country=="ROU",])


eur_type<-tidy(eur)  %>% filter(term != "(Intercept)") %>%  mutate(model = "UKR, BIH (n=658)")
nrow(gi[gi$country=="UKR" | gi$country=="BIH",])


noneu_d_type<-tidy(noneu_d)  %>% filter(term != "(Intercept)") %>% mutate(model = "JPN, KOR (n=455)")
nrow(gi[gi$country=="JPN" | gi$country=="KOR",])


noneu_ld_type<-tidy(noneu_ld)  %>% filter(term != "(Intercept)") %>%  mutate(model = "IND, IDN, MEX (n=857)")
nrow(gi[gi$country=="IDN" | gi$country=="IN" | gi$country=="MEX",])


eu_type<-tidy(eu)  %>% filter(term != "(Intercept)") %>% mutate(model = "EU (n=1774)")
nrow(gi[gi$country=="ESP" | gi$country=="ITA"|gi$country=="NLD" | gi$country=="GBR"|gi$country=="CZE" | gi$country=="POL" | gi$country=="ROU",])


noneu_type<-tidy(noneu)  %>% filter(term != "(Intercept)") %>% mutate(model = "Non-EU (n=2376)")
nrow(gi[gi$country=="MEX" | gi$country=="IDN" | gi$country=="IND"|gi$country=="JPN" | gi$country=="KOR"|gi$country=="UKR" | gi$country=="BIH",])


countrygr_l_type<-rbind(TOT_type, eu_sw_type, eu_e_type, eur_type, noneu_d_type, noneu_ld_type, eu_type, noneu_type)

countrygr_l_type<-countrygr_l_type %>% mutate(sign=ifelse(model=="Total" & p.value<0.05, TRUE, FALSE)) %>% 
  group_by(term) %>% mutate(sign_5=max(sign), sign=ifelse(sign_5==0, "P>0.05 (aggr. model)", "P<0.05 (aggr. model)"), sign=as.factor(sign)) %>% filter(model!="Total")


table(countrygr_l_type$term)


#### 2 c2a2 Country characteristics ####

gi<-gi[gi$type2!="No answer",]


tot<-probitmfx(formula = langjob_full_type_fe, data=gi,
                atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
                start = NULL, control = list())

germ<-probitmfx(formula = langjob_full_type_fe, data=gi[gi$country=="NLD" | gi$country=="GBR" | gi$country=="IND",],
                atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
                start = NULL, control = list())



ngerm<-probitmfx(formula = langjob_full_type_fe, data=gi[gi$country=="ESP" | gi$country=="ITA" | gi$country=="CZE" |gi$country=="ROU" 
                                                 | gi$country=="BIH" | gi$country=="MEX"| gi$country=="IND"| gi$country=="UKR"
                                                 | gi$country=="JPN" | gi$country=="KOR" | gi$country=="POL", ],
                 atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
                 start = NULL, control = list())

hi<-probitmfx(formula = langjob_full_type_fe, data=gi[gi$country=="ESP" | gi$country=="ITA"| gi$country=="GBR" | gi$country=="NLD" | gi$country=="CZE" | gi$country=="POL" | gi$country=="JPN"| gi$country=="KOR" ,],
              atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
              start = NULL, control = list())

umi<-probitmfx(formula = langjob_full_type_fe, data=gi[gi$country=="ROU" | gi$country=="BIH" | gi$country=="MEX",],
   atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL,
start = NULL, control = list())

lmi<-probitmfx(formula = langjob_full_type_fe, data=gi[gi$country=="IDN" | gi$country=="IND"| gi$country=="UKR" ,], 
atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
start = NULL, control = list())

eur<- probitmfx(formula = langjob_full_type_fe, data=gi[gi$country=="UKR" | gi$country=="BIH",], 
                atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
                start = NULL, control = list())

eu<-probitmfx(formula = langjob_full_type_fe, data=gi[gi$country=="ESP" | gi$country=="ITA"|gi$country=="NLD" | gi$country=="GBR"|gi$country=="CZE" | gi$country=="POL" | gi$country=="ROU",], 
              atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
              start = NULL, control = list())

noneur<- probitmfx(formula = langjob_full_type_fe, data=gi[gi$country=="MEX" | gi$country=="IDN" | gi$country=="IND"|gi$country=="JPN" | gi$country=="KOR",], 
                   atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
                   start = NULL, control = list())

cultclose<- probitmfx(formula = langjob_full_type_fe, data=gi[gi$country=="JPN" | gi$country=="BIH" | gi$country=="CZE"|gi$country=="IDN" | gi$country=="UKR"|gi$country=="KOR" | gi$country=="ITA",], 
                      atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
                      start = NULL, control = list())

cultdist<- probitmfx(formula = langjob_full_type_fe, data=gi[gi$country=="MEX" | gi$country=="IND" | gi$country=="ESP"|gi$country=="NLD" | gi$country=="ROU"|gi$country=="POL" | gi$country=="GBR",], 
                     atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
                     start = NULL, control = list())


stargazer(germ$fit, 
         ngerm$fit,
          umi$fit, 
          lmi$fit,
         hi$fit, 
         eu$fit,
          eur$fit,
          noneur$fit,
         cultclose$fit,
         cultdist$fit,
         coef = list(germ$mfxest[,1], 
                     ngerm$mfxest[,1],
                      lmi$mfxest[,1], 
                      umi$mfxest[,1],
                     hi$mfxest[,1], 
                     eu$mfxest[,1],
                      eur$mfxest[,1],
                      noneur$mfxest[,1],
                     cultclose$mfxest[,1],
                     cultdist$mfxest[,1]
                     ),
         se = list(germ$mfxest[,2], 
                   ngerm$mfxest[,2],
                    lmi$mfxest[,2], 
                    umi$mfxest[,2],
                   hi$mfxest[,2], 
                   eu$mfxest[,2],
                    eur$mfxest[,2],
                    noneur$mfxest[,2],
                   cultclose$mfxest[,2],
                   cultdist$mfxest[,2]
                   ),
         column.labels = c("Germanic", "Non-Germanic",
                           "Lower-middle income", "Upper-middle income", 
                           "High income", "EU", 
                           "European (non-EU)", "Non-European",
                           "Culturally close", "Culturally far"
                           ),
         header=TRUE,
         p.auto=FALSE,
         style="default",
         nobs=TRUE,
         align=TRUE, 
         no.space=TRUE, 
         single.row=FALSE,
         model.names = FALSE,
         dep.var.labels   = "Professional use of German",
         covariate.labels= c(    "Investment",
                                 "Age: under 35 years",
                                 "Gender: female",
                                 "Gender: n/a",
                                 "Children",
                                 "Partner (native German)",
                                 "Partner (other native)",
                                 "Occ.: high appl./low comm. skills",
                                 "Occ.: high appl./high comm. skills",
                                 "Occ.: in education",
                                 "Occ.: other occ./no answer",
                                 "University degree",
                                 "Risk attitude",
                                 "Patience",
                                 "English speaker"),
         omit = c("Constant", "country"),
         font.size = "small",
         add.lines = list(c("Country FE", "Yes", "Yes","Yes","Yes","Yes","Yes","Yes","Yes", "Yes", "Yes")),
         omit.stat = c("aic", "ll"),
         omit.table.layout = "n")


germ_type<-tidy(germ)  %>% filter(term != "(Intercept)") %>%  mutate(model = "Germanic")
ngerm_type<-tidy(ngerm)  %>% filter(term != "(Intercept)") %>%  mutate(model = "Non-Germanic")

umi_type<-tidy(umi)  %>% filter(term != "(Intercept)") %>%  mutate(model = "Upper-middle income")
hi_type<-tidy(hi)  %>% filter(term != "(Intercept)") %>%  mutate(model = "High income")
lmi_type<-tidy(lmi)  %>% filter(term != "(Intercept)") %>%  mutate(model = "Lower-middle income")

eu_type<-tidy(eu)  %>% filter(term != "(Intercept)") %>% mutate(model = "EU")
eur_type<-tidy(eur)  %>% filter(term != "(Intercept)") %>% mutate(model = "Non-EU (European)")
noneur_type<-tidy(noneur)  %>% filter(term != "(Intercept)") %>% mutate(model = "Non-EU (non-European)")

cultclose_type<-tidy(cultclose)  %>% filter(term != "(Intercept)") %>%  mutate(model = "Cuturally close")
cultdist_type<-tidy(cultdist)  %>% filter(term != "(Intercept)") %>%  mutate(model = "Culturally dist.")

TOT_type<-tidy(tot)  %>% filter(term != "(Intercept)") %>% mutate(model = "Total")

countrygr_l_type<-rbind(TOT_type, ngerm_type, germ_type, lmi_type, umi_type, hi_type, eu_type, eur_type, noneur_type, cultclose_type, cultdist_type)

countrygr_l_type<-countrygr_l_type %>% mutate(sign=ifelse(model=="Total" & p.value<0.05, TRUE, FALSE)) %>% 
  group_by(term) %>% mutate(sign_5=max(sign), sign=ifelse(sign_5==0, "P>0.05 (aggr. model)", "P<0.05 (aggr. model)"), sign=as.factor(sign)) %>% filter(model!="Total")


p_countrygroup<-dwplot(subset(countrygr_l_type,
                              (  countrygr_l_type$term=="typeTRUE" |
                                 countrygr_l_type$term=="factor(age)TRUE" |
                                 countrygr_l_type$term=="female1" | 
                                 countrygr_l_type$term=="children_d_naTRUE" | 
                                 countrygr_l_type$term=="part1" | 
                                 countrygr_l_type$term=="part2" | 
                                 countrygr_l_type$term=="occupationac1" | 
                                 countrygr_l_type$term=="occupationac2" | 
                                 countrygr_l_type$term=="occupationac3" | 
                                 countrygr_l_type$term=="degreeTRUE" |
                                 countrygr_l_type$term=="risk" | 
                                 countrygr_l_type$term=="patient" |
                                 countrygr_l_type$term=="englishTRUE"
                              )),
                       vline = geom_vline(xintercept = 0, colour = "grey60", linetype = 2), dodge_size= 0.7,
                       dot_args = list(aes(shape =as.factor(sign)), size=4)) +
  scale_x_continuous(limits = c(-0.2, 0.4))+
  scale_y_discrete(   labels=c("typeTRUE" = "Investment",
                               "factor(age)TRUE" = "Age: under 35 years",
                               female1 = "Gender: female",                       
                               children_d_naTRUE = "Children", 
                               "part1" = "Partner (native German)",                       
                               "part2" = "Partner (other native)",
                               degreeTRUE= "University degree",
                               "occupationac1" = "Occ.: high appl./low comm. skills",
                               "occupationac2" = "Occ.: high appl./high comm. skills",
                               "occupationac3" = "Occ.: in education",
                               risk = "Risk attitude", 
                               patient = "Patience",
                               "englishTRUE" = "English speaker"
                                ))+
  xlab("AME")+
  theme(legend.title = element_blank(),
        axis.text=element_text(size=10))+
  scale_color_grey(guide=guide_legend(reverse = TRUE))

pdf("../graphics/langjob_countrychar.pdf", paper="a4", width = 12, height = 14)
p_countrygroup
dev.off()

#### 2 c3 leave one country out ####

TOT<-probitmfx(formula = langjob_full_type2_fe, data=gi, atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
BIH<-probitmfx(formula = langjob_full_type2_fe, data=gi[gi$country!="BIH",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
CZE<-probitmfx(formula = langjob_full_type2_fe, data=gi[gi$country!="CZE",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
ESP<-probitmfx(formula = langjob_full_type2_fe, data=gi[gi$country!="ESP",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
GBR<-probitmfx(formula = langjob_full_type2_fe, data=gi[gi$country!="GBR",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
ITA<-probitmfx(formula = langjob_full_type2_fe, data=gi[gi$country!="ITA",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
JPN<-probitmfx(formula = langjob_full_type2_fe, data=gi[gi$country!="JPN",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
KOR<-probitmfx(formula = langjob_full_type2_fe, data=gi[gi$country!="KOR",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
NLD<-probitmfx(formula = langjob_full_type2_fe, data=gi[gi$country!="NLD",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
POL<-probitmfx(formula = langjob_full_type2_fe, data=gi[gi$country!="POL",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
ROU<-probitmfx(formula = langjob_full_type2_fe, data=gi[gi$country!="ROU",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
IND<-probitmfx(formula = langjob_full_type2_fe, data=gi[gi$country!="IND",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
IDN<-probitmfx(formula = langjob_full_type2_fe, data=gi[gi$country!="IDN",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
UKR<-probitmfx(formula = langjob_full_type2_fe, data=gi[gi$country!="UKR",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())
MEX<-probitmfx(formula = langjob_full_type2_fe, data=gi[gi$country!="MEX",], atmean = FALSE, robust = TRUE, clustervar1 = NULL, clustervar2 = NULL, 
               start = NULL, control = list())




stargazer(TOT$fit, 
          BIH$fit,
          CZE$fit, 
          ESP$fit,
          GBR$fit, 
          ITA$fit,
          JPN$fit, 
          KOR$fit,
          NLD$fit, 
          POL$fit,
          ROU$fit, 
          IND$fit,
          IDN$fit, 
          UKR$fit,
          MEX$fit, 
          coef = list(TOT$mfxest[,1], 
                      BIH$mfxest[,1],
                      CZE$mfxest[,1], 
                      ESP$mfxest[,1],
                      GBR$mfxest[,1], 
                      ITA$mfxest[,1],
                      JPN$mfxest[,1], 
                      KOR$mfxest[,1],
                      NLD$mfxest[,1], 
                      POL$mfxest[,1],
                      ROU$mfxest[,1], 
                      IND$mfxest[,1],
                      IDN$mfxest[,1], 
                      UKR$mfxest[,1],
                      MEX$mfxest[,1]),
          se = list(TOT$mfxest[,2],
                    BIH$mfxest[,2],
                    CZE$mfxest[,2],
                    ESP$mfxest[,2],
                    GBR$mfxest[,2],
                    ITA$mfxest[,2],
                    JPN$mfxest[,2],
                    KOR$mfxest[,2],
                    NLD$mfxest[,2],
                    POL$mfxest[,2],
                    ROU$mfxest[,2],
                    IND$mfxest[,2],
                    IDN$mfxest[,2],
                    UKR$mfxest[,2],
                    MEX$mfxest[,2]),
          column.labels = c("TOT", "BIH", "CZE", "ESP",  "GBR", "ITA", "JPN", "KOR", "NLD", "POL", "ROU", "IND", "IDN", "UKR", "MEX"),
          header=FALSE,
          style="default",
          dep.var.labels   = "Professional use of German",
          covariate.labels= c(    "Domestic labour market",
                                  "Educational and labour migration",
                                  "Personal reasons",
                                  "Cultural interest",
                                  "Age: under 35 years",
                                  "Gender: female",
                                  "Gender: n/a",
                                  "Children",
                                  "Partner (native German)",
                                  "Partner (other native)",
                                  "Occ.: in education",
                                  "Occ.: not in lab. market",
                                  "University degree",
                                  "Risk attitude",
                                  "Patience",
                                  "Intern. applic. of education"
          ),
          nobs=TRUE,
          align=TRUE, 
          no.space=TRUE, 
          single.row=TRUE,
          model.names = FALSE,
          omit = c("Constant", "country", "empstat4"),
          font.size = "small",
          add.lines = list(c("Country FE", "Yes", "Yes", "Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes")),
          notes= "Average marginal effects. Heteroscedasticity robust White standard errors in parentheses.",
          omit.stat = c("aic", "ll"))


TOT_type<-tidy(TOT)  %>% filter(term != "(Intercept)") %>% mutate(model = "Total")
BIH_type<-tidy(BIH)  %>% filter(term != "(Intercept)") %>% mutate(model = "BIH (n=110)")
CZE_type<-tidy(CZE)  %>% filter(term != "(Intercept)") %>% mutate(model = "CZE (n=280)")
ESP_type<-tidy(ESP)  %>% filter(term != "(Intercept)") %>% mutate(model = "ESP (n=395)")
GBR_type<-tidy(GBR)  %>% filter(term != "(Intercept)") %>% mutate(model = "GBR (n=274)")
ITA_type<-tidy(ITA)  %>% filter(term != "(Intercept)") %>% mutate(model = "ITA (n=186)")
JPN_type<-tidy(JPN)  %>% filter(term != "(Intercept)") %>% mutate(model = "JPN (n=183)")
KOR_type<-tidy(KOR)  %>% filter(term != "(Intercept)") %>% mutate(model = "KOR (n=189)")
NLD_type<-tidy(NLD)  %>% filter(term != "(Intercept)") %>% mutate(model = "NLD (n=60)")
POL_type<-tidy(POL)  %>% filter(term != "(Intercept)") %>% mutate(model = "POL (n=121)")
ROU_type<-tidy(ROU)  %>% filter(term != "(Intercept)") %>% mutate(model = "ROU (n=197)")
IND_type<-tidy(IND)  %>% filter(term != "(Intercept)") %>% mutate(model = "IND (n=373)")
IDN_type<-tidy(IDN)  %>% filter(term != "(Intercept)") %>% mutate(model = "IDN (n=485)")
UKR_type<-tidy(UKR)  %>% filter(term != "(Intercept)") %>% mutate(model = "UKR (n=458)")
MEX_type<-tidy(MEX)  %>% filter(term != "(Intercept)") %>% mutate(model = "MEX (n=281)")

gi %>% count(country) %>% arrange(-n)

country_l_type<-rbind(TOT_type, 
                      ESP_type, GBR_type, CZE_type, ITA_type, POL_type, ROU_type, NLD_type,
                      BIH_type,  UKR_type, 
                      MEX_type, IND_type, IDN_type,
                      KOR_type, JPN_type)

country_l_type<-country_l_type %>% mutate(sign=ifelse(model=="Total" & p.value<0.05, TRUE, FALSE)) %>% 
  group_by(term) %>% mutate(sign_5=max(sign), sign=ifelse(sign_5==0, "P>0.05 (aggr. model)", "P<0.05 (aggr. model)"), sign=as.factor(sign)) 

