For the letter C, we’ll talk about the coalesce function. If you’re familiar with SQL, you may have seen this function before. It combines two or more variables into a single column, and is a way to deal with missing data. When you give it a list of variables, it selects the first non-missing value it finds. Because of that, order of entry of those variables is important.
I recently used this function at work to get last performance on an item. That is, diplomates in our program take spaced assessments, with repetition of items (same content, but slightly different item wording) that they answered incorrectly. If they got the initial item correct, they may never see a related item again (although over time they will), but if they were incorrect, they may get related items once or more times to see if they’re learning. So we have some people who will have a missing value for the repeated item and others who will have correct/incorrect. The coalesce function allowed me to get their final performance on item content by telling it to first check the repeated item column and then, if that’s missing, to look at the initial item column.
How can we use the coalesce function for the reading dataset? I noticed that for 17 books in the dataset, I forgot to supply a rating, so they’re showing up as 0. Let’s select those titles, and I can figure out how I’d like to rate them.
reads2019 <- read_csv("~/Downloads/Blogging A to Z/SarasReads2019.csv", col_names = TRUE)
unrated <- reads2019 %>%
filter(MyRating == 0)
##  "Bird Box (Bird Box, #1)"
##  "Elevation"
##  "Glinda of Oz (Oz, #14)"
##  "It"
##  "Just Evil (Evil Secrets Trilogy, #1)"
##  "Oryx and Crake (MaddAddam, #1)"
##  "Precarious Pasta (Cozy Corgi Mysteries, #14)"
##  "Redshirts"
##  "Rinkitink in Oz (Oz, #10)"
##  "Summerdale"
##  "The 5 Love Languages: The Secret to Love That Lasts"
##  "The Long Mars (The Long Earth, #3)"
##  "The Magic of Oz (Oz, #13)"
##  "The Marvelous Land of Oz (Oz, #2)"
##  "The Scarecrow of Oz (Oz, #9)"
##  "The Tin Woodman of Oz (Oz, #12)"
##  "Tik-Tok of Oz (Oz, #8)"
So now I want to generate a variable with my new ratings, and merge it into my reads dataset.
unrated$NewRating <- c(3, 5, 4, 4, 2, 4, 4, 5, 4, 3, 3, 4, 4, 5, 3, 3, 4)
unrated <- unrated %>%
reads2019 <- reads2019 %>%
left_join(unrated, by = "Book.ID")
Finally, we’ll create our final ratings variable by coalescing the two ratings variables. I want it to first look at the new rating column, so it can capture those updates. For rows missing that variable (because I already rated them), it will look next at the original rating variable.
reads2019 <- reads2019 %>%
mutate(FinalRating = coalesce(NewRating, MyRating))
## 2 3 4 5
## 2 9 51 25
No more 0s!