setwd("C:/Users/Adam/Desktop/paleo_msc/semester_1/rconsolidation/lecture9/2023-02-19_carnivores_pbdb")

# 1. Download this file: carnivore_families.csv
# 2. Read it into R with read.csv()! Check its structure and familiarize yourself with the columns. Every row represents one occurrence of a taxon in a collection. These usually belong to a species, but the fossils are sometimes not that easy to identifiy. For this reason we will look into the genera only.
carnivores <- read.csv("data/carnivore_families.csv")

# 3. List the unique families in the table (column family). How many families are there? Do all names make sense?
# Two entries are wrong here
unique(carnivores$family)

# 4. This dataset, as most compiled data, needs some cleaning. We can make this set considerably better if we omit bad entries (ie. subset to that part, where column value is not equal to these). Write subsetting multiple commands to omit a. entries where the family is "" (empty string); b. family is "NO_FAMILY_SPECIFIED"; c. genus is "" (empty string)!
# 4b. Cleaning the family subset
sub1 <- carnivores[which(carnivores$family!=""), ]
subFamily <- sub1[which(sub1$family!="NO_FAMILY_SPECIFIED"), ]

# confirm that this indeed has omitted the bad entries
unique(subFamily$family)

# a different solution with logical operators
subFamily2 <- carnivores[
  which(carnivores$family!="" & carnivores$family!="NO_FAMILY_SPECIFIED"),]

# a third solution.
whatYouDontWant <- carnivores[
  which(carnivores$family %in% c("","NO_FAMILY_SPECIFIED" )),
]

subFamily3 <- carnivores[
  which(! carnivores$family %in% c("","NO_FAMILY_SPECIFIED" )),
]
nrow(subFamily3)

# 4b. Make sure that the genus entries are also clean! Some Entries are not resolved
# to the genus level, in these cases the genus column is equal to ""
# List out the genus entries!
unique(subFamily$genus)

# Omit these "" genera before going forward!

# 5. Subset your data to the family "Canidae". Count the number of genera in this family!
  
# 6. Make sure that the unique list of families do not contain the bad entries! Using a for loop, repeat step 5 and count the number of genera for every family!
  
# 7. Plot a histogram of the resulting vector!
  
# 8. Which family has the highest number of genera? What is the median number of genera in a family?
  
# 9. Ensure that your script works without human intervention! Clean your code, close your R session, and repeat all calculations with the script that you wrote!
