Little useless-useful R functions – Vanishing sentences


[This article was first published on R – TomazTsql, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)


Want to share your content on R-bloggers? click here if you have a blog, or here if you don’t.

Let’s play with some words. More in particular with vanishing words.

Using two packages: ggplot2 and gganimate we will construct a animation (looped), where sentences will be vanishing, word by word. A nice way to train the ggplot animations.

The function is combination of data frame wrangling and visualizations:

vanishing_sentence <- function(sentence, output_file = NULL, interval = 0.5) {
  
  words <- unlist(strsplit(sentence, " "))
  vanishing_order <- sample(seq_along(words))
  
  sentence_data <- data.frame(
    word = words,
    position = seq_along(words),
    vanish_step = match(seq_along(words), vanishing_order)
  )
  
  # sequence
  animation_data <- do.call(rbind, lapply(1:(max(sentence_data$vanish_step) + 1), function(step) {
    sentence_data %>%
      mutate(visible = ifelse(vanish_step >= step, TRUE, FALSE)) %>%
      group_by(position) %>%
      summarize(word = ifelse(visible, word, ""), .groups = "drop") %>%
      mutate(step = step)
  }))
  
  p <- ggplot(animation_data, aes(x = position, y = 1, label = word)) +
    geom_text(size = 6, hjust = 0.5, vjust = 0.5, fontface = "bold") +
    theme_void() +
    theme(
      plot.margin = margin(1, 1, 1, 1, "cm"),
      plot.background = element_rect(fill = "white", color = NA)
    ) +
    transition_states(step, transition_length = interval,state_length = 1) +
    enter_fade() +
    exit_fade() +
    ease_aes("linear") 
  
  
  # render and save
  if (!is.null(output_file)) {
    anim <- animate( p,nframes = length(words) + 10, fps = 10,width = 800,height = 400, renderer = gifski_renderer(output_file) )
    return(anim)
  } else {
    animate(
      p,
      nframes = length(words) + 10,
      fps = 10,
      width = 800,
      height = 400
    )
  }
}

And once you have the function available in your environment, run the function (two ways – to save it into windows output or into a file):

sentence <- "This sentence will gradually vanish - word by word"
# save to file
vanishing_sentence(sentence, output_file = "vanishing_sentence.gif")
# save to output
vanishing_sentence(sentence)

As always, the complete code is available on GitHub in  Useless_R_function repository. The sample file in this repository is here (filename: Vanishing_sentence.R). Check the repository for future updates.

Happy new year 2025! Carry on with R-coding and stay healthy!





Source link

Related Posts

About The Author

Add Comment