Code Snippets R

Short texts R 🧑‍💻 Code snippets R ✍️ Reading lists R 👀

Media consumption (cable news channels) by mean party identification

library(tidyverse) setwd(“C:/Users/Mark’s computer/iCloudDrive/Non-paper R projects/CCES 2020”) cces % filter(pid7 < 8) %>% drop_na(CC20_300b_4, CC20_300b_5, CC20_300b_6) %>% summarize(mean_msnbc = weighted.mean(pid7[CC20_300b_6 == 1], w = commonweight[CC20_300b_6 == 1]), mean_cnn = weighted.mean(pid7[CC20_300b_4 == 1], w = commonweight[CC20_300b_4 == 1]), mean_fox = weighted.mean(pid7[CC20_300b_5 == 1], w = commonweight[CC20_300b_5 == 1])) Outlet

Model selection using CV

# snippet: not all code included # revised loop to do cross-validation for (m in 1:length(allModels)) { allpredicted = rep(NA,n) # storage for honest predictions for (ii in 1: nfolds) { # ii is an easier string to search for index groupii = (cvgroups == ii) trainset = bodyfat[!groupii,] # all data EXCEPT for group […]

gtsummary mcnemar.test

library(gtsummary) library(dplyr) set.seed(1234) d1 % group_by(r1) %>% mutate(id = row_number()) %>% ungroup() d2 %>% filter(complete.cases(.)) %>% group_by(id) %>% filter(n() == 2) %>% ungroup() %>% tbl_summary(by = r1, include = -id) %>% add_p(test = r2 ~ “mcnemar.test”, group = id) # tbl_summary() returned p-value = 0.6. mcnemar.test(d1$r1, d1$r2) # > mcnemar.test(d1$r1, d1$r2) # # McNemar’s Chi-squared […]

Google Trends plot for popular TV shows

# https://rstudio-pubs-static.s3.amazonaws.com/155168_61e1f687681d44e4988ce28b7f6ec13b.html # https://www.leehbi.com/blog/2019-06-04-Google-Trends-with-R library(“dplyr”) library(“ggplot2”) library(“gtrendsR”) library(“extrafont”) loadfonts(device = “win”) # Define search terms terms