



```{r Library load}

require(tidyverse)
require(stargazer)


```




```{r Data load}


mean(1:5)

sum(1:5)

## Single datapoints
smol_data <- 9

smol_data

smol_data + 1

smol_data ^ (1/2)

smol_data2 <- smol_data * 2



## Vectors
vector1 <- c(smol_data, 
             smol_data2)

vector2 <- c(4,8,10)

vector3 <- c(1,2,3)


## Dataframes, matrices, tibbles

big_df <- data.frame(vector1,
                     vector2)


big_df <- data.frame(vector2,
                     vector3)

view(big_df)

## Tibbles are usually cleaner to work with (don't worry about this for now)

big_df <- tibble(vector2,
                  vector3)

```




```{r Cars datasets}


## Save as new object so we can access/edit

view(cars)
cars_df <- cars


## Get details about data, packages, etc.
?cars

## Get column names
names(cars)


## Open viewer panel
view(cars)



## Get a bigger dataset now

?mtcars

cars_df <- mtcars

glimpse(cars_df)
names(cars_df)



## The group_by and reframe trick
## Note that this requires tidyverse/dplyr
## It also uses the pipe operators (%>%) 

diag_df <- cars_df %>%
  group_by(cyl) %>%
  reframe(count = n() )


diag_df <- cars_df %>%
  group_by(hp) %>%
  reframe(count = n() )


diag_df <- cars_df %>%
  group_by(cyl, hp) %>%
  reframe(count = n() )


```


```{r Plots and Regressions with Cars dataset}

## Base R:

plot(data = cars_df, 
     mpg ~ cyl)


## Basic GGplot

ggplot(data = cars_df, aes(x = cyl, y = mpg)) + 
  geom_point(aes(color = am))



## Clean data beforehand for better output

cars_df$Cylinder <- factor(cars_df$cyl,  levels = c(4,6,8))

?mtcars


cars_df <- cars_df %>%
mutate(Transmission = ifelse(am == 0, "Automatic", "Manual"))


cars_df <- cars_df %>% rename(MPG = mpg)


ggplot(data = cars_df,
       aes(x = Cylinder,
           y = MPG)) +
  geom_point(aes(color = Transmission))


```


```{r Regressions}

## Basic regression, old data


lm1 <- lm(data = cars_df,
          formula = hp ~ cyl)

lm2 <- lm(data = cars_df,
          hp ~ cyl + am)


stargazer(lm1, lm2,
          type = "text",
          out = "cars_table_olddata.txt")


## Basic regression, cleaned variables

lm1 <- lm(data = cars_df,
          hp ~ Cylinder)


lm2 <- lm(data = cars_df,
          hp ~ Cylinder + Transmission)


stargazer(lm1, lm2,
          type = "text",
          out = "cars_table_cleandata.txt")

stargazer(lm1, lm2,
          type = "latex",
          out = "cars_table_cleandata.txt"
          )

?stargazer

```



