TDM 10100: Project 5 Question 1 examples

R has a built-in vector of the 50 states:

state.abb

We can read in the data about breweries:

library(data.table)
myDF <- fread("/anvil/projects/tdm/data/beer/breweries.csv")

and we can look at the first 6 rows of the data:

head(myDF)

The breweries in the US usually have a state listed with them.

The first six values of the state column are:

head(myDF$state)

Data frames are two-dimensional objects, with rows and columns.

When indexing a data frame, we refer to the rows before a comma, and we refer to the rows after a comma.

We can leave things blank, when we want all rows or all columns.

For instance, these are some rows in which the state column is found in state.abb:

head(myDF[myDF$state %in% state.abb, ])

These are some rows in which the country column is equal to US:

head(myDF[myDF$country == "US", ])

There are 236 rows in which the country is equal to US but the state is not found in state.abb. Notice that the exclamation mark means "not". In this case, for instance, we are checking to see if the state column is not found in state.abb.

head(myDF[(myDF$country == "US") & (!(myDF$state %in% state.abb)), ])

To see that there are 236 such rows (and there are still 7 columns), we check the dimension of this data frame:

dim(myDF[(myDF$country == "US") & (!(myDF$state %in% state.abb)), ])

Another way to check the same thing is with subset. When we use subset, R knows that we are looking at columns in myDF (in this example), so we do not need to specify myDF when checking the country and the state:

Here are the first 6 rows, using subset:

head(subset(myDF, (country == "US") & (!(state %in% state.abb))))

and here are the same number of rows and columns:

dim(subset(myDF, (country == "US") & (!(state %in% state.abb))))

Now we can also remove DC as well, by specifying that we want breweries whose country is US and whose state is not in state.abb and also is not equal to DC:

myDF[(myDF$country == "US") & (!(myDF$state %in% state.abb)) & (myDF$state != "DC"), ]

or equivalently:

subset(myDF, (country == "US") & (!(state %in% state.abb)) & (state != "DC"))

There are only 33 such breweries:

dim(subset(myDF, (country == "US") & (!(state %in% state.abb)) & (state != "DC")))