Some time back in the #rstat twitter-verse, there was a silly challenge thrown out there to see who could use the map functions from the purrr package to write one of the famous children book. It did took me quite a while to have it right to the punction and indentation, but here was my attempts to programmatically write the famous “Brown Bear, Brown Bear” story in R.

This version is nice because it outputs a .txt file that can then be read by the computer using one of its voice ;-)

animals <- c("Brown Bear", "Red Bird", "Yellow Duck", "Blue Horse", "Green Frog", "Purple Cat", 
               "White Dog", "Black Sheep", "Goldfish", "Teacher", "Children")

q <- function(x) paste0(x, ", \n", x, ", \n", "What do you see? \n")
a <- function(x) paste0("I see a ", tolower(x), "\n", " looking at me.")
qa <- function(animals){
  qs <- map_chr(animals, q)
  as <- map_chr(animals[-1], a)
  as[length(as)] <- gsub("a ", "", as[length(as)])

  final <- paste0("a ", tolower(animals[-length(animals)]), ',')
  final[length(final)] <- paste0("and ", gsub(",", "", final[length(final)]), 
                               " looking at us. \n That's what we see.")
  as[length(as)+1] <- "we see "
  cat(paste(qs, as, collapse = "\n"), final, file = "Brownbear.txt")


And the final version looks like this:

Brown Bear, Brown Bear, What do you see? I see a red bird looking at me. Red Bird, Red Bird, What do you see? I see a yellow duck looking at me. Yellow Duck, Yellow Duck, What do you see? I see a blue horse looking at me. Blue Horse, Blue Horse, What do you see? I see a green frog looking at me. Green Frog, Green Frog, What do you see? I see a purple cat looking at me. Purple Cat, Purple Cat, What do you see? I see a white dog looking at me. White Dog, White Dog, What do you see? I see a black sheep looking at me. Black Sheep, Black Sheep, What do you see? I see a goldfish looking at me. Goldfish, Goldfish, What do you see? I see a teacher looking at me. Teacher, Teacher, What do you see? I see children looking at me. Children, Children, What do you see? we see a brown bear, a red bird, a yellow duck, a blue horse, a green frog, a purple cat, a white dog, a black sheep, a goldfish, and a teacher looking at us. That’s what we see.

You can download the .text file here