Skip to content

Instantly share code, notes, and snippets.

@dougspencer
Created August 27, 2025 05:55
Show Gist options
  • Select an option

  • Save dougspencer/9f7d7ade62429b3f0c9580dadc445169 to your computer and use it in GitHub Desktop.

Select an option

Save dougspencer/9f7d7ade62429b3f0c9580dadc445169 to your computer and use it in GitHub Desktop.
Empirical Legal Studies (Fall 2025)
#####
# CODE SNIPPETS FROM IN-CLASS EXERCISES
# Empirical Legal Studies (Fall 2025)
#####
##########
## reading in datasets
# when reading in CSV files you need to assign to an object
# filename is the full path on your computer
x <- read.csv("filename.csv")
# reading in a dataset from the Internet -- include full URL
x <- read.csv("http://www.dougspencer.org/data/penguins.csv")
# when loading an RData file the object will be howeer it was saved
load("filename.RData")
##########
## saving datasets
# must specifcy which object you are saving (here "x")
write.csv(x, file = "filename.csv")
save(x, file = "filename.RData")
##########
## summarizing data: Election Law Professors
# read in dataset
x <- read.csv("~/Downloads/election_profs.csv")
# see the dimensions of the data (rows x columns)
dim(x)
# preview the first 6 rows of the data
head(x)
# evaluate casebook usage (equivalent to Excel Pivot Table)
table(x$Casebook)
# evaluate casebook usage by years taught
table(x$Casebook, x$Years)
##########
# subsetting data
x <- x[2, 5] # this will just show you the 2d row and the 5th column
x <- x[2, ] # this will show the entire second row (blank column argument means all columns)
x <- x[ , 5] # this will show you all rows of column 5
x[x$Years == 11, -2] # this will show all rows where year = 2011 and all columns except columns 2
# saving to new object
new.object <- x[x$Year == 11, ] # this will create new object of the subset for year = 11 and all columns (because columns is blank)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment