Final Project - Xhulia Turkaj

Week 3 R Bridge Course MSDS 2023

In this project I wanted to explore the relationship between the average numbers of hours spent by an individual watching tv and their overall happiness level.

The dataset I am using has data from interviews conducted from 1994 all the way to 2006.

Reading and loading the dataset from github

week_3_data <- read.csv("https://raw.githubusercontent.com/xhuliaturkaj/BridgeMSDS/main/happiness.csv",  header = TRUE, row.names = 1)

happiness R Documentation Description

Format A data.frame with 17137 observations on 33 variables:

year: gss year for this respondent

workstat: work force status

prestige: occupational prestige score

divorce: ever been divorced or separated

widowed: ever been widowed

educ: highest year of school completed

reg16: region of residence, age 16

babies: household members less than 6 yrs old

preteen: household members 6 thru 12 yrs old

teens: household members 13 thru 17 yrs old

income: total family income

region: region of interview

attend: how often r attends religious services

happy: general happiness

owngun: =1 if own gun

tvhours: hours per day watching tv

vhappy: =1 if ‘very happy’

mothfath16: =1 if live with mother and father at 16

black: =1 if black

gwbush04: =1 if voted for G.W. Bush in 2004

female: =1 if female

blackfemale: black*female

gwbush00: =1 if voted for G.W. Bush in 2000

occattend: =1 if attend is 3, 4, or 5

regattend: =1 if attend is 6, 7, or 8

y94: =1 if year == 1994

y96:

y98:

y00:

y02:

y04:

y06: =1 if year == 2006

unem10: =1 if unemployed in last 10 years

NA

Source https://www.cengage.com/cgi-wadsworth/course_products_wp.pl?fid=M20b&product_isbn_issn=9781111531041

summary(week_3_data)
##       year        workstat            prestige       divorce         
##  Min.   :1994   Length:17137       Min.   :17.00   Length:17137      
##  1st Qu.:1996   Class :character   1st Qu.:33.00   Class :character  
##  Median :1998   Mode  :character   Median :43.00   Mode  :character  
##  Mean   :1999                      Mean   :43.88                     
##  3rd Qu.:2004                      3rd Qu.:51.00                     
##  Max.   :2006                      Max.   :86.00                     
##                                    NA's   :854                       
##    widowed               educ          reg16               babies      
##  Length:17137       Min.   : 0.00   Length:17137       Min.   :0.0000  
##  Class :character   1st Qu.:12.00   Class :character   1st Qu.:0.0000  
##  Mode  :character   Median :13.00   Mode  :character   Median :0.0000  
##                     Mean   :13.32                      Mean   :0.2071  
##                     3rd Qu.:16.00                      3rd Qu.:0.0000  
##                     Max.   :20.00                      Max.   :6.0000  
##                     NA's   :44                         NA's   :101     
##     preteen           teens           income             region         
##  Min.   :0.0000   Min.   :0.0000   Length:17137       Length:17137      
##  1st Qu.:0.0000   1st Qu.:0.0000   Class :character   Class :character  
##  Median :0.0000   Median :0.0000   Mode  :character   Mode  :character  
##  Mean   :0.2557   Mean   :0.1814                                        
##  3rd Qu.:0.0000   3rd Qu.:0.0000                                        
##  Max.   :6.0000   Max.   :7.0000                                        
##  NA's   :101      NA's   :88                                            
##     attend             happy              owngun             tvhours      
##  Length:17137       Length:17137       Length:17137       Min.   : 0.000  
##  Class :character   Class :character   Class :character   1st Qu.: 1.000  
##  Mode  :character   Mode  :character   Mode  :character   Median : 2.000  
##                                                           Mean   : 2.904  
##                                                           3rd Qu.: 4.000  
##                                                           Max.   :24.000  
##                                                           NA's   :5343    
##      vhappy         mothfath16        black           gwbush04    
##  Min.   :0.0000   Min.   :0.000   Min.   :0.0000   Min.   :0.000  
##  1st Qu.:0.0000   1st Qu.:0.000   1st Qu.:0.0000   1st Qu.:0.000  
##  Median :0.0000   Median :1.000   Median :0.0000   Median :1.000  
##  Mean   :0.3069   Mean   :0.693   Mean   :0.1384   Mean   :0.502  
##  3rd Qu.:1.0000   3rd Qu.:1.000   3rd Qu.:0.0000   3rd Qu.:1.000  
##  Max.   :1.0000   Max.   :1.000   Max.   :1.0000   Max.   :1.000  
##                   NA's   :5                        NA's   :15207  
##      female        blackfemale         gwbush00       occattend    
##  Min.   :0.0000   Min.   :0.00000   Min.   :0.000   Min.   :0.000  
##  1st Qu.:0.0000   1st Qu.:0.00000   1st Qu.:0.000   1st Qu.:0.000  
##  Median :1.0000   Median :0.00000   Median :1.000   Median :0.000  
##  Mean   :0.5591   Mean   :0.08905   Mean   :0.522   Mean   :0.285  
##  3rd Qu.:1.0000   3rd Qu.:0.00000   3rd Qu.:1.000   3rd Qu.:1.000  
##  Max.   :1.0000   Max.   :1.00000   Max.   :1.000   Max.   :1.000  
##                                     NA's   :13701   NA's   :273    
##    regattend           y94              y96              y98        
##  Min.   :0.0000   Min.   :0.0000   Min.   :0.0000   Min.   :0.0000  
##  1st Qu.:0.0000   1st Qu.:0.0000   1st Qu.:0.0000   1st Qu.:0.0000  
##  Median :0.0000   Median :0.0000   Median :0.0000   Median :0.0000  
##  Mean   :0.1312   Mean   :0.1737   Mean   :0.1683   Mean   :0.1637  
##  3rd Qu.:0.0000   3rd Qu.:0.0000   3rd Qu.:0.0000   3rd Qu.:0.0000  
##  Max.   :1.0000   Max.   :1.0000   Max.   :1.0000   Max.   :1.0000  
##  NA's   :273                                                        
##       y00             y02               y04               y06        
##  Min.   :0.000   Min.   :0.00000   Min.   :0.00000   Min.   :0.0000  
##  1st Qu.:0.000   1st Qu.:0.00000   1st Qu.:0.00000   1st Qu.:0.0000  
##  Median :0.000   Median :0.00000   Median :0.00000   Median :0.0000  
##  Mean   :0.162   Mean   :0.07989   Mean   :0.07802   Mean   :0.1742  
##  3rd Qu.:0.000   3rd Qu.:0.00000   3rd Qu.:0.00000   3rd Qu.:0.0000  
##  Max.   :1.000   Max.   :1.00000   Max.   :1.00000   Max.   :1.0000  
##                                                                      
##      unem10     
##  Min.   :0.000  
##  1st Qu.:0.000  
##  Median :0.000  
##  Mean   :0.318  
##  3rd Qu.:1.000  
##  Max.   :1.000  
##  NA's   :5796

Installing and loading the needed packages

library(ggplot2)
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union

My two main variables of interest are happiness and tv hours watched on average Here I am checking their type I transformed the happiness variable as an ordered categorical variable and saved it as ordered_happines

class(week_3_data$happy)
## [1] "character"
unique(week_3_data$happy)
## [1] "pretty happy"  "very happy"    "not too happy"
#Defining the ordered levels for the variable since class is character

ordered_levels <- c("not too happy", "pretty happy", "very happy")

# Convert to ordered categorical variable

ordered_happiness <- factor(week_3_data$happy, levels = ordered_levels, ordered = TRUE)

week_3_data$ordered_happiness <- ordered_happiness

class(week_3_data$tvhours)
## [1] "integer"

I initially wanted to visually explore how/if the levels of happiness have changed throughout the years

frequency_table <- table(week_3_data$year, week_3_data$ordered_happiness)



# Create the percentage distribution directly from the frequency_table

percentage_data <- prop.table(frequency_table, margin = 1) * 100

# Convert the percentage_data table to a data frame
frequency_data <- as.data.frame(percentage_data)

# Create the stacked bar plot with percentages


ggplot(frequency_data, aes(x = as.factor(Var1), y = Freq, fill = Var2)) +
  geom_bar(stat = "identity") +
  labs(title = "Weighted Frequency of Happiness Levels for Each Year",
       x = "Year",
       y = "Percentage") +
  scale_fill_manual(values = c("not too happy" = "red", "pretty happy" = "yellow", "very happy" = "green")) +
  theme_minimal()

As seen from the stacked bar plot there doesn’t seem to be any significant shifts on the happiness level distribution throughout the years

Next I wanted to visually explore how the average of tv hours watched by an individual during the day has changed throughout the years

class(week_3_data$tvhours)
## [1] "integer"
# Calculate the mean of tvhours per each year
mean_tvhours_by_year <- week_3_data %>%
  group_by(year) %>%
  summarise(mean_tvhours = mean(tvhours, na.rm = TRUE))

# Create a plot with a logarithmic y-axis scale
ggplot(mean_tvhours_by_year, aes(x = year, y = mean_tvhours)) +
  geom_line() +
  geom_point() +
  labs(title = "Average TV Hours Watched per Day Over the Years",
       x = "Year",
       y = "Mean TV Hours")+
  scale_y_continuous(limits = c(2.5, 3.5), breaks = seq(0, 5, by = 0.5))

As seen by the graph there isn’t a significant change on the average hours of tv watched per day throughout the years.

Next I will create a subset of the dataset by eleminating some of the columns that aren’t neccesary to answer our questions of interest.

columns_to_remove <- c("reg16", "region", "owngun", "attend", "mothfath16", "gwbush00", "blackfemale", "occattend", "regattend", "prestige", "divorce", "widowed", "happy") 

subset_week_3 <- week_3_data[, -which(names(week_3_data) %in% columns_to_remove)]
 head(subset_week_3)

Next I want to visually explore the relationship between happiness and tv hours watched per day

ggplot(subset_week_3, aes(x = ordered_happiness, y = tvhours)) +
  geom_boxplot() +
  labs(title = "TV Hours by Happiness Level",
       x = "Happiness Level",
       y = "TV Hours") +
  scale_x_discrete(labels = c("not too happy", "pretty happy", "very happy")) 
## Warning: Removed 5343 rows containing non-finite values (`stat_boxplot()`).

Judging from the box plot I can assume that there may be a negative correlation between TV hours watches and level of happiness. I am hypothesizing that individuals that watch little hours of TV per day have a higher chance of exhibiting a higher happiness level than those that watch to many hours of TV and vice versa.

A visual representation is not enough to determine that so I will run statistical tests to run my hypothesis. Considering we have a numerical variable and an ordered categorical variable the right test to run is a Kruskal-Wallis test

##Kruskal-Wallis test

library(stats)

# Kruskal-Wallis test
kruskal_wallis_result <- kruskal.test(tvhours ~ ordered_happiness, data = subset_week_3)

print(kruskal_wallis_result)
## 
##  Kruskal-Wallis rank sum test
## 
## data:  tvhours by ordered_happiness
## Kruskal-Wallis chi-squared = 142.6, df = 2, p-value < 2.2e-16

Based on the results of the Kruskal-Wallis test, we would reject the null hypothesis, concluding that there are significant differences in tvhours across the different levels of ordered_happiness. In other words, the median TV hours watched per day vary significantly among the three levels of happiness (“not so happy”, “little happy”, and “very happy”).

The Kruskal-Wallis test only test a correlational relationship and does not indicate a casual relationship. In other words we can’t determine weather the hours of tv watched cause the level of happiness or vice versa.

##Ordinal Logistic Regression

I decided to run an ordinal logistic regression since it is suitable for predicting the relationship between an ordinal dependent variable (the ordinal categorical level) and one or more independent variables (the integer variable).

library(MASS)
## 
## Attaching package: 'MASS'
## The following object is masked from 'package:dplyr':
## 
##     select
library(effects)
## Loading required package: carData
## lattice theme set by effectsTheme()
## See ?effectsTheme for details.
# Perform ordinal logistic regression
model <- polr(ordered_happiness ~ tvhours, data = subset_week_3)
print(summary(model))
## 
## Re-fitting to get Hessian
## Call:
## polr(formula = ordered_happiness ~ tvhours, data = subset_week_3)
## 
## Coefficients:
##            Value Std. Error t value
## tvhours -0.09008   0.008038  -11.21
## 
## Intercepts:
##                            Value    Std. Error t value 
## not too happy|pretty happy  -2.3555   0.0391   -60.2917
## pretty happy|very happy      0.5765   0.0297    19.4043
## 
## Residual Deviance: 21578.26 
## AIC: 21584.26 
## (5343 observations deleted due to missingness)
# Create the proportional odds plot for all three levels of ordered_happiness
plot_effects <- effect(term = "tvhours", mod = model, type = "response", at = list(tvhours = unique(subset_week_3$tvhours)))
## 
## Re-fitting to get Hessian
# Plot the proportional odds plot with all three lines
plot(plot_effects, xlab = "TV Hours", ylab = "Predicted Probability", main = "Proportional Odds Plot", col.line = "blue")

The x-axis of the graph represents the values of tvhours, which is the number of hours spent watching TV. The y-axis represents the predicted probability of each happiness level. The proportional odds plot illustrates how the predicted probabilities of each happiness level change as the number of TV hours watched varies.

Conclusion

The ordinal logistic regression results show that there is a significant association between happiness levels and the number of hours spent watching TV per day. The results indicate that the number of hours spent watching TV (tvhours) is associated with changes in the odds of being in different happiness levels (ordered_happiness). The negative coefficient suggests that more TV hours are generally associated with lower odds of being in a higher happiness level.