Site icon R-bloggers

How to create an interactive booklist with automatic Amazon affiliate links in R?

[This article was first published on R on Stats and R, 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.
  • Introduction

    Booklists are a useful way to share the books you have read and which you recommend to other readers and/or to promote the books you have written. It can be as simple as a list of book titles displayed on your personal website or blog. You may however wish to present this list of books in a more sophisticated way, such as in a table with titles, authors and links to buy it for instance.

    In this blog post I show you how to create an interactive booklist with automatic Amazon affiliate links in R. By interactive, I mean a booklist which allows users to search for books by title or author (like this booklist for instance). Moreover, by automatic Amazon affiliate links, I mean URLs (with your affiliate link of course) that redirect directly to the book in question on the Amazon webstore, without manually creating a link for each book.

    This technique is especially helpful for those of you who have hundreds of books in their list as you will need to create the URL only once and it will adapt automatically to all books.

    Requirements

    In order to build this augmented booklist with your affiliate link, you need:

    • an Amazon associates account. Register here if you do not have an account yet
    • a list of books (which you recommend and/or written by you)

    Create a booklist

    You have two options:

    1. create it in Excel then import it into R
    2. create it directly in R

    Create it in Excel then import it

    The easiest way is to follow these steps:

    1. open an Excel file and fill it in with two columns: (i) one with the titles and (ii) a second with the authors (see figure below)
    2. save it in a .csv format (in Excel, File > Save As… > choose the CSV file format and save it)
    3. import it into R (see how to import a .csv file if you struggle with the importation)
    4. (if you need to edit the list in the future, edit it directly in the .csv file and not in the Excel file)

    Here is how you booklist created in Excel should look like (with I suppose more books in yours):

    Step 1: Booklist created in Excel

    We now import it into RStudio and rename the dataset as dat (see here why I always use a generic name instead of more specific names):

    dat <- read.csv("booklist.csv", # name of your file with .csv extension
      header = TRUE, # names of variables are present
      sep = ","
    ) # values are separated by a comma

    You can always check that your booklist is correctly imported by running head(name_of_dataset) or View(name_of_dataset).

    Create it directly in R

    You can create your booklist directly in R with the command data.frame():

    # Create the data frame named dat
    dat <- data.frame(
      "Title" = c(
        "A Random Walk Down Wall Street",
        "Naked Statistics",
        "Freakonomics"
      ),
      "Author" = c(
        "Burton G. Malkiel",
        "Charles Wheelan",
        "Steven D. Levitt and Stephen J. Dubner"
      ),
      stringsAsFactors = FALSE
    )
    # Print the data frame
    dat
    ##                            Title                                 Author
    ## 1 A Random Walk Down Wall Street                      Burton G. Malkiel
    ## 2               Naked Statistics                        Charles Wheelan
    ## 3                   Freakonomics Steven D. Levitt and Stephen J. Dubner

    Make it interactive

    In order to be able to search for books by author or title, we use the datatable() command from the DT package. Below the table with the default options:

    library(DT)
    datatable(dat)

    Let’s improve this table by:

    • removing row numbers
    • adding a filter on top of “Title” and “Author” columns
    • adding the possibility to copy or download the table
    • show only first 5 entries instead of 10
    • order books by title in ascending order
    datatable(dat,
      rownames = FALSE, # remove row numbers
      filter = "top", # add filter on top of columns
      extensions = "Buttons", # add download buttons
      options = list(
        autoWidth = TRUE,
        dom = "Blfrtip", # location of the download buttons
        buttons = c("copy", "csv", "excel", "pdf", "print"), # download buttons
        pageLength = 5, # show first 5 entries, default is 10
        order = list(0, "asc") # order the title column by ascending order
      )
    )

    Add URLs with your affiliate link to the table

    We are now going to add URLs (with your affiliate link) which depend on the title and author of the book in the interactive table presented above. For this, we first need to extract the affiliate link which will serve as the base of the URL, then add the title and author of the book at then end of the URL. The fact that we add the title and author of the book at the end of the URL makes it automatic. Indeed, the final URL will redirect to the search page of the book (thanks to the title and author of the book as keywords) and with your affiliate link included (as we use the affiliate link as the base URL).

    Extract affiliate link

    To extract the affiliate link, follow these steps (see figures below for help):

    1. Go to your Amazon associates account
    2. Click on Product Linking > Link to Any Page
    3. Click on the tab “Link to Search Results”
    4. Choose “Books & Textbooks” for the product line
    5. Enter any keywords you want and a name for your link (the two will be change later so it does not matter what you type)
    6. Click on the button “Get HTML”
    7. Copy in your clipboard (CTRL+c on Windows or cmd+c on Mac) the code displayed in the Preview (right pane)

    Step 2: Link to Any Page on Amazon associates account

    Step 3 to 7: Create Amazon affiliate link for a search page

    The code you just copied should look like this (not exactly the same though as it includes your personal affiliate link):

    <a target="_blank" href="https://www.amazon.com/gp/search?ie=UTF8&tag=antoinesoetew-20&linkCode=ur2&linkId=a587bdd780cbbfb6d3f4569f7fb358fc&camp=1789&creative=9325&index=books&keywords=BOOK TITLE">BOOK TITLE</a><img src="//ir-na.amazon-adsystem.com/e/ir?t=antoinesoetew-20&l=ur2&o=1" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" />

    From this long code, remove everything which follows keywords= but keep keywords= (that is why it does not matter what you typed in step 5 above). Following our example, we are left with this piece of code:

    <a target="_blank" href="https://www.amazon.com/gp/search?ie=UTF8&tag=antoinesoetew-20&linkCode=ur2&linkId=a587bdd780cbbfb6d3f4569f7fb358fc&camp=1789&creative=9325&index=books&keywords=

    Copy this shortened code.

    Append the book title and author to make it automatic

    We are now going to concatenate (i.e., append several character strings together) the Amazon affiliate link (the code we just copied), the title and author of the book and then a closing HTML tag with the paste0() command. The result will be a URL which takes the affiliate link as the base and the title and author of the book as keywords, making it automatic and adapted for every book in your booklist. To do this, run the following command in R:

    # Do not mix " and ', they are different in this case!
    link <- paste0(
      '<a target="_blank" href="https://www.amazon.com/gp/search?ie=UTF8&tag=antoinesoetew-20&linkCode=ur2&linkId=a587bdd780cbbfb6d3f4569f7fb358fc&camp=1789&creative=9325&index=books&keywords=', # affiliate link
      dat$Title, " + ", dat$Author, # book title and author
      '">Amazon</a>' # closing HTML tag
    )

    Your links should look something like this, with same affiliate links and closing tags for all books but with different keywords, corresponding to book titles and authors:

    head(link)
    ## [1] "<a target=\"_blank\" href=\"https://www.amazon.com/gp/search?ie=UTF8&tag=antoinesoetew-20&linkCode=ur2&linkId=a587bdd780cbbfb6d3f4569f7fb358fc&camp=1789&creative=9325&index=books&keywords=A Random Walk Down Wall Street + Burton G. Malkiel\">Amazon</a>"   
    ## [2] "<a target=\"_blank\" href=\"https://www.amazon.com/gp/search?ie=UTF8&tag=antoinesoetew-20&linkCode=ur2&linkId=a587bdd780cbbfb6d3f4569f7fb358fc&camp=1789&creative=9325&index=books&keywords=Naked Statistics + Charles Wheelan\">Amazon</a>"                   
    ## [3] "<a target=\"_blank\" href=\"https://www.amazon.com/gp/search?ie=UTF8&tag=antoinesoetew-20&linkCode=ur2&linkId=a587bdd780cbbfb6d3f4569f7fb358fc&camp=1789&creative=9325&index=books&keywords=Freakonomics + Steven D. Levitt and Stephen J. Dubner\">Amazon</a>"

    Add links to the interactive table

    Now that the URLs are specific to each book, we can add them to the interactive table built earlier:

    dat$Link <- link

    Finally, we can display the interactive table with titles, authors and their URLs:

    datatable(dat,
      rownames = FALSE, # remove row numbers
      filter = "top", # add filter on top of columns
      extensions = "Buttons", # add download buttons
      options = list(
        autoWidth = TRUE,
        dom = "Blfrtip", # location of the download buttons
        buttons = c("copy", "csv", "excel", "pdf", "print"), # download buttons
        pageLength = 5, # show first 5 entries, default is 10
        order = list(0, "asc") # order the title column by ascending order
      ),
      escape = FALSE # to make URLs clickable
    )

    This is exactly the same code than before except that we need to add escape = FALSE to make URLs clickable.

    Final result

    Check that everything works properly by clicking on different links. If you did not miss any steps, it should redirect you to the Amazon store with the title and author of the book in the search bar and thus the book in question appearing in the search results.

    Thanks for reading. I hope this article helped you to build an interactive booklist with an automated affiliate link to each of the book in your list.

    As always, if you have a question or a suggestion related to the topic covered in this article, please add it as a comment so other readers can benefit from the discussion.

    To leave a comment for the author, please follow the link and comment on their blog: R on Stats and R.

    R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
    Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.