alexpghayes
alexpghayes

Reputation: 703

How to embed tweets in R markdown documents being knit to HTML?

It is fairly easy to embed tweets into blog post using the blogdown R package and Hugo shortcodes as described at https://bookdown.org/yihui/blogdown/content.html.

I would like to embed tweets in an R markdown document that is being knit to a standalone HTML document. What is the best way to do this? It looks like Twitter provides an Embed Tweet functionality that I can use interactively to get HTML to embed a tweet, but I need to do this programmatically, given a tweet id.

Upvotes: 5

Views: 1434

Answers (1)

Ari Anisfeld
Ari Anisfeld

Reputation: 816

For people who don't want to go to twitter, the thread includes recommendations for two packages. twittrmd and twitterwidget. I was able to get twittrmd to work as follows:

Install packages

This was the hard part, because the CRAN webshot2 repo wasn't compatible with my R environment.

devtools::install_github("gadenbuie/tweetrmd")

# necessary if your output type is not html (as far as I can tell)
devtools::install_github("rstudio/webshot2")

# this is a webshot2 requirement
install.packages("magick")

Use packages

With these packages you can capture a screenshot by

library(twittrmd)
include_tweet("https://twitter.com/nomadj1s/status/1294390352904966151")

If your output type is not html, tweetrmd will rendered as a png or pdf. In any case, I think you can only see the tweet upon knitting.

More info is available on the github, including helper functions to build twitter urls from a username and tweet_id and ideas about how to use memoise to keep a copy of the tweet in the case that it's removed from twitter.

Upvotes: 3

Related Questions