2 == 1+1

1/2 == .5

2 == 3

2/3 == .6666 

vec <- c(1,2,3,4,5)

vec == 3

2 > 3

2 < 3

vec > 3

vec >= 3

vec <= 3

sum(vec >= 3)

mean(vec >= 3)

2 == 3 #FALSE

2 != 3 #TRUE

!(2 == 3) #TRUE. essentially the same as the one above

2 > 3 #FALSE

!(2 > 3) #TRUE

!c(T, F, T,T,T, F)

(2 == 2) & (3 == 3) #TRUE

(2 == 2) & (3 == 2) #FALSE

(2 == 2) | (3 == 2) #TRUE

(2 == 8) | (3 == 2) #FALSE

buffalo.springfield <- c("stills", "martin","palmer","furay","young")
csn <- c("crosby","stills","nash")
csny <- c("crosby","stills","nash","young")

buffalo.springfield %in% csn
buffalo.springfield %in% csny

buffalo.springfield[buffalo.springfield %in% csny]

#What members of Buffalo Springfield weren't in CSNY?
buffalo.springfield[!(buffalo.springfield %in% csny)]

coin <- c("H","T")

sample(coin, 1)


sample(coin, 1)
sample(coin, 1)
sample(coin, 1)
sample(coin, 1)
sample(coin, 1)

for(i in 1:4){
  print(i)
}

for(i in 1:1000){
  sample(coin, 1)
}

result <- NA
for(i in 1:1000){
 result[i] <- sample(coin, 1)
}
head(result)

result <- NA
for(i in 1:1000){
 result[i] <- sample(coin, 1)=="H"
}
head(result)

mean(result)

dice <- c(1,2,3,4,5,6)

#Using the replace=T option because each time we sample from the dice
#we want all sides to be available
sum(sample(dice, 3, replace=T))
#Same with the coin
sample(coin, 2, replace=T)

#This one is easy: is the sum greater than 12
sum(sample(dice, 3, replace=T))>=12

#For the coin we want to see if each entry is equal to "H", but only return one true if
#both of them are H. We can do that with all()
sample(coin,2, replace=T)=="H"

all(sample(coin,2, replace=T)=="H")

#And then we want to know if both conditions are met: 

sum(sample(dice, 3, replace=T))>=12 & all(sample(coin,2, replace=T)=="H")



result <- NA
for(i in 1:1000){
  result[i] <- sum(sample(dice, 3, replace=T))>=12 & all(sample(coin,2, replace=T)=="H")
}

mean(result)


coin <- c(0,1)
samp <- sample(coin, 1000, replace=T, prob=c(.7,.3))
#Lower bound less than .3 and upper bound greater than .3?
t.test(samp)$conf.int[1]<.3 & t.test(samp)$conf.int[2]>.3

result <- NA
for(i in 1:1000){
  samp <- sample(coin, 1000, replace=T, prob=c(.7,.3))
#Lower bound less than .3 and upper bound greater than .3?
result[i] <- t.test(samp)$conf.int[1]<.3 & t.test(samp)$conf.int[2]>.3
}
mean(result)


library(tidyverse)
sm <- rio::import("https://github.com/marctrussler/IIS-Data/raw/refs/heads/main/NBCJun25.Rds", trust=T)
glimpse(sm)

attributes(sm$q0004)

attributes(sm$q0043)

attributes(sm$q0039_0001)
attributes(sm$q0039_0002)


sm <- sm |>
    rename(trump_approval = q0004,
           white = q0039_0001,
           hispanic = q0039_0002,
           black = q0039_0003,
           asian = q0039_0004,
           mena = q0039_0005,
           hawaiin.pi = q0039_0006,
           amerindian = q0039_0007,
           other.race = q0039_0008,
           hispanic_origin = q0040,
           education = q0042,
           income = q0043,
           sex = q0044
    ) 
names(sm)

attributes(sm$trump_approval)
sm |> 
  mutate(trump_approval = case_when(trump_approval==1 ~ "Strongly approve",
                                    trump_approval==2 ~ "Somewhat approve",
                                    trump_approval==3 ~ "Somewhat disapprove",
                                    trump_approval==4 ~ "Strongly disapprove"),
         trump_approval_f = factor(trump_approval, levels = c("Strongly approve","Somewhat approve", "Somewhat disapprove","Strongly disapprove"))) -> temp

table(temp$trump_approval)

table(temp$trump_approval_f)

mt.attributes.to.labels <- function(dat){
dat %>%
    mutate(across(everything(), ~ {
      labels <- attr(.x, "labels")
      if (!is.null(labels)) {
        factor(.x, levels = labels, labels = names(labels))
      } else {
        .x
      }
    })) 
}

sm.out <- mt.attributes.to.labels(sm)

head(sm.out)

weighting.targets <- rio::import("https://github.com/marctrussler/IIS-Data/raw/refs/heads/main/NationalACSTargets.Rds", trust=T)
weighting.targets$race
weighting.targets$age4
weighting.targets$sex
weighting.targets$educ

#This one's fine
table(sm.out$sex)
#
table(sm.out$age4)

sm.out |> 
  mutate(educ = case_when(education %in% c("Did not complete high school", "High school or G.E.D.") ~ "Hs Or Less",
                          education %in% c("Some college, but no degree", "Associate’s degree, occupational or vocational program", 
                                           "Associate’s degree, academic program") ~ "Some College",
                          education=="Bachelor’s degree" ~ "College", 
                          education=="Post graduate degree" ~ "Postgrad"),
         educ = factor(educ, levels = c("Hs Or Less","Some College","College", "Postgrad")),
         age4 = factor(age4, levels = c("18-29","30-44","45-64", "65+"))) -> sm.out
table(sm.out$education, sm.out$educ)

#Using the "make your own function" ability of mutate here to recode each of these variable to be false if NA and true if not NA. 
sm.out |> 
  mutate(across(white:other.race, \(x) !is.na(x))) |>
  rowwise() |> 
  mutate(multiracial = sum(white,hispanic, black, asian, mena, hawaiin.pi, amerindian, other.race)>=2) -> sm.out

sm.out |> 
  mutate(race = case_when(hispanic==T | hispanic_origin=="Yes" ~ "Hispanic",
                          white==T & multiracial==F  ~ "White",
                          black==T & multiracial==F ~ "Black", 
                          asian==T & multiracial==F   ~ "Asian",
                          mena==T | hawaiin.pi==T | amerindian==T | other.race==T | multiracial==T ~ "Other"    
                          ),
         race = factor(race, levels = c("White","Hispanic","Black","Asian","Other"))) -> sm.out

#Checks
table(sm.out$race, sm.out$hispanic)
table(sm.out$race, sm.out$hispanic_origin)

#Drop race questions we don't need: 
sm.out |> 
  select(-white:-hispanic_origin, -multiracial) -> sm.out


#To install pewmethods first: 
#install.packages("devtools")
#library(devtools)
#Then run
#install_github("pewresearch/pewmethods", build_vignettes = TRUE)

#Weights:
sm.out$weight <-  pewmethods::rake_survey(sm.out, weighting.targets)

table(sm.out$trump_approval)
prop.table(table(sm.out$trump_approval))

mean(sm.out$trump_approval=="Strongly approve", na.rm=T)

table(approval = sm.out$trump_approval, race = sm.out$race)

prop.table(table(approval = sm.out$trump_approval, race = sm.out$race))

prop.table(table(approval = sm.out$trump_approval, race = sm.out$race),2)

prop.table(table(approval = sm.out$trump_approval, race = sm.out$race),1)

pewmethods::get_totals("trump_approval", sm.out, wt="weight", na.rm=T, include_unw = T)

pewmethods::get_totals("race", sm.out, wt="weight", na.rm=T, include_unw = T)

weighting.targets$race

pewmethods::get_totals("trump_approval", sm.out, wt="weight", by="race", na.rm=T)

pewmethods::get_totals("trump_approval", sm.out, wt="weight", by="race", na.rm=T) |> 
  pivot_longer(cols=White:Other, 
               names_to = "race", values_to = "percent") |> 
ggplot(aes(x = trump_approval, y = percent, fill = trump_approval)) +
  geom_col() +
  facet_wrap(~race, scales = "free_y") +
  labs(
    title = "Trump Approval by Race",
    x = "Approval Level",
    y = "Percent"
  ) +
  theme_minimal() +
  theme(
    legend.position = "none",
    axis.text.x = element_text(angle = 45, hjust = 1)
  )

