Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

Sunday, May 17, 2020

Lesson 10: Send Email or Text by R-Script using RDCOMClient

Lesson 10 - Send Emails by R-Script using RDCOMClient

Have you ever wanted to get a text message or an email when your script finished? I have many times! Well, look no farther because if you use Microsoft Outlook desktop application, here is a solution that will work perfectly! This solution uses an R Package called RDCOMClient maintained by http://www.omegahat.net. RDCOMClient is a very useful package because it can be used to interact with COM Objects associated with Microsoft Office applications such as Outlook, Word, Excel, Access, and Power Point. If you've written any Visual Basic scripts, you've likely used COM Objects at some point. Basically, this means you can programatically interact with these applications from R, opening up a whole list of possiblities for you! It's a very useful package and I use it daily!

STEP #1 - The first thing you'll need to do is download the lastest Java SE 8 Runtime Environment (JRE) for your Operating System (OS). You might be asking "Why Java SE 8?" Well, the simple answer is because that's what I know has worked for myself and my friends. Make sure if you're running 64-bit R that you download the 64-bit version of the JRE. You can find the JRE for your OS here.

STEP #2 - After you've successfully installed the JRE for your OS, the next thing you'll need to do is install the rJava library package. I've found the easiest way to do this is right from your console

install.packages("rJava")
library(rJava)

Honestly, rJava can be a bit of a hassle to get setup, but if you run into issues, go checkout stackoverflow.com. I used this site to help troubleshoot my issues with my installation.

STEP #3 - Once you have the JRE and a working rJava library, the next thing you need to do is get a copy of the the RDCOM Client library package. You can get it from one of two places. Either from the CRAN or you can navigate here and download the package version that matches your R version. Personally, I prefer downloading from the Omegahat site and then install it from the zip file. The name of the file will be "RDCOMClient_0.93-0.zip" for R 3.5 or RDCOMClient_0.94-0.zip for R 4.0. For a version that will work with an older version of R, navigate to the "old" directory.

Assuming you download the file from Omegahat, installation can be done by using the "Tools" menu "Install Packages..."



Then you'll want to browse to the location where you saved the RDCOMclient zip-file, select it, and click "Install".


STEP #4 - Once RDCOMClient has finished installing, you can run this code! Use an email address or use a phone number followed by carrier text message domains for sending text message(ATT is @mms.att.net, Sprint is @messaging.sprintpcs.com, and Verizon is @vtext.com, etc.)

# HEADER --------------------------------------------
#
# Author: Your Name
# Copyright (c) Your Name, 2019
# Email:  your_email@your_domain.com
# 
# Date: Today's Date
#
# Script Name: Email / Text Message with Microsoft Outlook
#
# Script Description: Create and send an email using Microsoft Outlook and RDCOMClient
#
#
# Notes:
# RDCOMClient is used to interact with COM Objects associated with Microsoft Office applications
# such as Outlook, Word, Excel, Access, and Powerpoint.
#

# Load Libraries
library(rJava)
library(RDCOMClient)

# Script to send text/email message
# access the Outlook application
OutApp <- COMCreate("Outlook.Application")

# create an email
outMail = OutApp$CreateItem(0)

# configure  email parameter
#carrier suffixes for sending to TEXT @mms.att.net, OR @messaging.sprintpcs.com, OR # @vtext.com
outMail[["To"]] = "your_email@someplace.com"

outMail[["subject"]] = "Testing! - An Email Message from R"

outMail[["body"]] = "Hey, it worked!!"

# unremark the next line to add attachment
# path_to_file = "some_file.pdf"
# outMail[["Attachments"]]$Add(path_to_file)

# unremark to change "from" (send from secondary mailbox)
# outMail[["SentOnBehalfOfName"]] = "your_secondary@someplace.com"

# send email or text
cat("Email message sent.\n\n")
outMail$Send()

RDCOMClient can do a whole lot more than just send emails, I encourage you to check it out and learn more about it!

Enjoy!
Have fun coding!

RdataGuy

Download the code for this lesson below!

Monday, November 18, 2019

Lesson 9: Random Number Generator - Part 2 (Shiny App)

Lesson 9: Random Number Generator - Part 2 (Shiny App)

Introduction

Well, here we go! Part 2 of our Random Number Generator RScript journey.

In this lesson we’re going to pick-up where we left off with the Random Number Generator RScript and now we’re going to take it to the next level by building a deployable Shiny Web Application. I’m really excited about this lesson!

Shiny Web Application Basics

Before we get started with developing our application, we need to cover some Shiny App basics.

The Shiny Cheat Sheet defines a Shiny Application as follows:
A Shiny app is a web page (UI) connected to a computer running a live R session (Server). Users can manipulate the UI, which will cause the server to update the UI’s displays (by running R code).

You might be asking… “What does this mean?” Well, it means that a Shiny App RScript has four basic sections.

  1. Section 1: Load the Shiny Library.
  2. Section 2: Create the HTML User Interface (UI) to collect user input.
  3. Section 3: Define the Server Logic (server) to utilize the collected user input to produce the desired output.
  4. Section 4: Run the Shiny App using the defined UI & server code.

Heres what these four basic sections look like in an RScript.

Now that you have a little better idea of what the RScript is doing, your next thought might be “How do I get this application on the web? I don’t have an R Server and I’m not planning on leaving my laptop connected to the internet 24/7/365 to be a server!”

Well don’t worry because RStudio offers a place for you to deploy and share your web applications! The name of this place is shinyapp.io and it’s a fantastic website for anyone interested in developing their own Shiny web applications. The site has access packages available for every level of need from the R Hobbiest to the Large Corporation.

Our Goal

Our end goal is to produce a Shiny Web Application using the code we wrote in Lesson 8. When we’re all done it should look a little something like this.

Shiny App

Step #1: Create the Application Script

Okay, so let’s dive in and create our Application Script file. This will be were we build the “guts” of the application using our code from Lesson 8.
To create the Shiny Web Application Script file also known as “app.R”, click on the “New File” button and select “Shiny Web App…”

New File --> Shiny Web App

This will bring up a window where you can name the application. You should know that you can’t have any spaces in the application name. So, instead of spaces, I use "_" or “-”. In this case, let’s name the application “random_numbers”. Then click the “Create” button.

Create Web App

When the “app.R” script file is generated, there will be example code in the file but we’re not going to use this code. We’re going to modify it to meet our needs. Here’s the code you get when you generate the “app.R” file.

Step #3: Add our code

Our Shiny Web App is divided into two areas:

  1. A User Interface (UI) that contains:
    1. A “Side Panel” with 4 user inputs and an action button for the user to press to start the random number generator.
      1. Numeric Input called “values” for number of values the user needs.
      2. Numeric Input called “rangeStart” for start of range of numbers to use.
      3. Numeric Input called “rangeEnd” for end of range of numbers to use.
      4. Two Radio Buttons called “dupes” for users to decide if they want to sample with replacement.
      5. Action Button called “do” for user to press to initiate the random number generator calculations on the server:
    2. A “Main Panel” where the rendered tabluar output called “randomNumbers” will be displayed.
  2. Server logic that contains:
    1. Reactive Event on the server that executes our code using the user’s 4 input values (e.g. values, rangeStart, rangeEnd, dupes) to generate random numbers once the user clicks on the “do” Action Button called “Generate!” and stores the generated numbers in a variable called “random_data”.

    2. Render the reactive event data, “random_data”, into a tablular output format called “randomNumbers” which is displayed in the UI’s Main Panel.

Here’s what the finished code looks like.

# HEADER --------------------------------------------
#
# Author: RDataGuy
# Copyright (c) RDataGuy, 2019
# Email:  rdataguy@gmail.com
# 
# Date: 2019-11-16
#
# Shiny App Name: Random Number Generator
#
# Shiny App Description: Generate a defined number of random values
# for a given range of numbers.
#
#
# Notes:
# This is a single file Shiny App.
#

# LOAD LIBRARIES ------------------------------------
library(shiny)


# USER INTERFACE ------------------------------------
# Define UI for application that generates a list of random numbers
ui <- fluidPage(

    # Application title
    titlePanel("Random Number Generator"),

    # Sidebar with inputs for the randome number generator
    sidebarLayout(
        sidebarPanel(
            numericInput("values",
                      "Number of Values:",
                      5),
            
            numericInput("rangeStart",
                      "Range Start",
                      1),
            
            numericInput("rangeEnd",
                      "Range End",
                      5),
            
            radioButtons("dupes",
                         "Duplicates?",
                         choices = c(TRUE,FALSE),
                         selected = FALSE),
            br(), # adds a blank line
            actionButton("do", "Generate!")
        ),

        # Show a table of random numbers using the Server's output called "randNumbers"
        mainPanel(
            tableOutput("randNumbers")
        )
    )
)


# SERVER INFORMATION --------------------------------
# Define server logic required to display table of random numbers
server <- function(input, output) {
    
    # Use an action button as an event to generate the list of random numbers
    random_data <- eventReactive(input$do, {  
        
        # Randomly sample values from the specified range
        numbers <- seq(input$rangeStart:input$rangeEnd)
        sample(numbers, input$values, replace = as.logical(input$dupes))
        
    })

    # Output the list of random numbers only AFTER the "Generate!" button is pressed
    output$randNumbers <- renderTable({
        random_data()
    }, rownames = FALSE, colnames = FALSE)
}


# RUN APPLICATION ----------------------------------
shinyApp(ui = ui, server = server)

Step #4: Test our Web Application

Okay! Let’s test it! To test your application, click on the “Run App” button. Run App Button

You should see a web page pop up. Try clicking on the “Generate!” button. You should see output similar to this.

Random Number Generator Test Results

Step #5: Deploy our Web Application

Alright! Time to deploy this baby!

  1. First, you need to install the “rsconnect” package & load the library:
  1. Next, you need to create a shinyapps.io account. If you have a Google or GitHub account, you can just sign in with that and setup your profile.

shinyapps.io Login

  1. Create a token on shinyapps.io so you can configure “rsconnect” so you can deploy your app to shinyapps.io from RStudio using the “rsconnect” package. Click on your profile pic in the upper right corner and click on the “tokens” option.

Create New Token

After you create your token you should see a window with your rsconnect configuration information.

Token

Click the copy to clipboard button and paste in your RStudio Console.

Rsconnect is now configured to deploy your application to shinyapps.io!

Next, go to your “app.R” script and click on the “Publish” button Publish Button or in your RStudio Console type “deployApp()”.

After you deploy your application the browser window should pop up with your newly deployed web application. Here’s mine for you check out.

Conclusion

I hope you enjoyed these last two lessons and found them helpful.

Enjoy!

Have fun coding!

RDataGuy

Download the code for this lesson below!