Showing posts with label OSX. Show all posts
Showing posts with label OSX. 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!

Saturday, September 15, 2018

Lesson 3: Vectors, Lists, Matrices, and Data Frames in R

Data structures are next on the list of things we need to discuss because they are central to just about everything we do in R.  Data structures in R come in four main flavors: vectors, lists, matrices and data frames.  We'll discuss each of these data structures this week, along with special cases of vectors, such as scalars and factors, as well as a special case of matrices, called arrays.

Okay, let's get started!

PART #1: VECTORS, SCALARS, AND FACTORS

Vectors are able to hold one kind of data type or mode (e.g. numeric, character).
Vectors can be created using the combine function "c()".
So, let's first create a vector with numeric data.

my_first_vector <- c(1, 2, 3, 4, 5)

Now let's create a vector with character data or strings.

my_second_vector <- c("Orange", "Apple", "Banana", "Pear", "Peach")

To reference an element or value in a vector use an index value enclosed in square brackets "[ ]".  For example, to reference the first element in the vector, use "[1]".

my_second_vector[1]

One can also create subsets of the original vector by using a continuous index range from x to y by using the following syntax "[x:y]".  For example, to create a new vector that is a subset of the second vector's last three items, use an index rand of "[3:5]".

my_third_vector <- my_second_vector[3:5]

You can also create a new vector that is a subset of the original vector's first and last items using the "[c(1,5)]".

my_fouth_vector <- my_second_vector[c(1,5)]


To add a value to a vector and create a new vector, use the combine function "c()" once again, referencing the original vector in the combine function.

my_fifth_vector <- c(my_second_vector, "Apricot")

Next we'll discuss Scalars.  Scalars are vectors with only one element
Pi in R is stored as a scalar.  You can test this by referencing it's "first" element

pi[1]

Factors are similar to vectors except a factor stores each unique value in the vector as a 'level' or category.  Factors can used to label or categorize your data.

Let's turn the fifth vector we created into a list of factors.

my_first_factors <- factor(my_fifth_vector)

PART #2: LISTS

Unlike vectors, lists are able to hold more than one kind of data type or mode (e.g. numeric, character).
Let's create a list with numeric and character data modes using the "list()" function.

my_first_list <- list(1, 2, 3, "car", "truck", "van")

Referencing values or elements in a list is similar to referencing element in a vector.  To reference the fourth element in the list use "[[4]]"

my_first_list[[4]]

Similar to vectors, one can also create subsets of the original list by using a continuous index range from x to y by using the following syntax "[x:y]".  For example, To create a new list that is a subset of the original list's last three items use the "[3:5]".

my_second_list <- my_first_list[3:5]

And again, similar to vectors, to create a new list that is a subset of the original list's first and last items use "[c(1,5)]".

my_third_list <- my_first_list[c(1,5)]

Finally, similar to vectors, to add a value to a list and create a new list, use the combine function "c()" once again, referencing the original list in the combine function.

my_fourth_list <- c(my_first_list, "suv")

PART #3: MATRICES AND ARRAYS

You may or may not remember matrices from high school or college math.  Matrices are (typically) numeric vectors with one or more dimensions.  A matrix can be produced from multiple vectors.

a <- c(1,2,3)
b <- c(4,5,6)
c <- c(7,8,9)

To create a matrix we use the "matrix()" function.  First, you should know that there are three parameters used by the "matrix()" function that define what the matrix looks like.  The "data" parameter allows you to specify what vectors to use for data using the "c()" function. The "nrow" and "ncol" allow you tell R how many rows and columns define the matrix.

So, let's create a matrix using the "matrix()" function and the three vectors above.

my_first_matrix <- matrix(data = c(a,b,c), nrow = 3, ncol = 3)

Similar to vectors and lists you can reference specific values in the matrix.  For instance, to reference the item in the first row of the third column in the matrix use "[1,3]".

my_first_matrix[1,3]

Now for the next exercise, we'll need to create a fourth vector.

d <- c(10,11,12)

To add the new vector "d" to "my_first_matrix" as an additional column you need to use the column bind or "cbind" function.

my_second_matrix <- cbind(my_first_matrix,d)

To add the new vector 'd' to 'my_first_matrix' as an additional row you need to use the row bind or "rbind" function.

my_third_matrix <- rbind(my_first_matrix,d)


Next, let's talk about arrays.  Arrays are just matrices with 3 or more dimensions.
To make our first array, let's make a vector with 27 items.  For example number values from 1 to 27.

my_first_array <- c(1:27)

Now to create the array, let's divide the vector up into three 3 x 3 matrices and stack them using the dimension or "dim" function and combine or "c()" function to specify how to structure the vector in to a 3-dimensional array.

dim(my_first_array) <- c(3,3,3)

Review the results of your first first array.

print(my_first_array)

PART #4: DATA FRAMES

Data frames are the last data structure we'll discuss this week.  Data frames are designed to hold tabular data.  They are similar to spreadsheets.  They have columns and rows and can store all data types.  Data frames can be built from vectors, lists, or matrices.  Let's build our first data frame from "my_first_vector" and "my_second_vector" using the "data.frame" function.  For this example, we're going also going to set a parameter called "stringsAsFactors" to FALSE.  This will make sure that the string data is saved as "character" data type rather than "factor" data type.

my_first_df <- data.frame(my_first_vector, my_second_vector, stringsAsFactors = FALSE)

We can also create data frames from lists, so we'll do that next
But, before we do that we have to create a list of vectors.

my_vector_list <- list(my_first_vector, my_second_vector)

When using lists to create a data frame, you need to use the "as.data.frame" function rather than the "data.frame" function.

my_other_df <- as.data.frame(my_vector_list, stringsAsFactors = FALSE)

Since the default column names are the vector names, let's rename the columns.

names(my_first_df) <- c("Quantity", "Fruit")

Using matrix notation, let see what's in row 3.

my_first_df[3,]

Now, Let see what's in column 2.

my_first_df[,2]

OR use the name of column 2 instead to also see what's in it.

my_first_df$Fruit

Next, Let's see what's in row 4, column 2.

my_first_df[4,2]

Finally, let's change the value in row 4, column 2 from "Pear" to "Plum".

my_first_df[4,2] <- "Plum"


Only one more step.  Let's save that script you just created by clicking on "File" -> "Save As..." and let's name your script "R_Lesson3.R"  Click "Save".
Congratulations!  You've completed Lesson 3!


DOWNLOAD CODE Here is the code from my GitHub gist "R Lesson 3 - Vectors, Lists, Matrices, and Data Frames in R" in case you'd rather just copy and paste it and then play around with it.



Sunday, September 9, 2018

Lesson 2: Working Directory & File Operations in R

So you got your first program behind you!  Now we'll take a look at how you can determine where R is storing your new script.  The following is a tutorial on how to determine your "working directory", set your working directory and then do some simple file operations while you're in the "working directory".

So, you might be asking "What exactly is the working directory"?  The working directory is where R-Studio saves your scripts as well as R-Studio's .Rdata files that contain workspace  settings and data so that you can load a past session and pick-up where you left off.  Additionally, the working directory is where R-Studio will look if you ask it to read a file if you do not provide an absolute path.

STEP#1 - CHECK YOUR WORKING DIRECTORY

To display the working directory in the R-Studio console you can use the 'getwd' function.

getwd()

My working directory is currently set to:

[1] "/Users/RGuy/Documents"

STEP#2 - SET YOUR WORKING DIRECTORY

Next, to change the working directory  to my Desktop in R-Studio, you can use the 'setwd' function.

work_directory = "~/Desktop"
setwd(work_directory)

STEP#3 - SEE CONTENTS OF WORKING DIRECTORY

Next, let's display the contents of our working directory
dir(work_directory)

The contents of my working directory currently are:
[1] "a.jpg"       "b.jpg"      "Documents"   "temp_submit"

STEP#4 - PERFORM VARIOUS FILE OPERATIONS

You can perform various file operations while in R-Studio. Let's store a list of the files and folders in the working directory and then do the following: a) Copy a file, b) Rename a file, c) Determine time file was last modified, and lastly d) Determine size of file. Store a list of the working directory's contents (files & folders)
directory_contents = dir(work_directory)

a. Copy 'a.jpg' and rename the it to 'a_copy.jpg'.  Remember that 'a.jpg was the first item list in the working directory contents. Therefore, since we stored the directory's content information in the 'directory_content' variable as a list, we can reference item #1 (a.jpg) in the list by typing 'directory_contents[1]'.
file.copy(directory_contents[1], "a_copy.jpg")

b. Next we'll rename 'a_copy.jpg' to 'c.jpg'
file.rename("a_copy.jpg", "c.jpg")

c. Now, we'll determine the date & time the file 'c.jpg' was last modified
file.mtime("c.jpg")

d. Finally, we'll see what the size of the file 'c.jpg' is in bytes.  NOTE: Divide value by 1,000 for kilobytes, and 1,000,000 for megabytes.
file.size("c.jpg")

STEP 5: SAVING YOUR SCRIPT

Only one more step.  Let's save that script you just created by clicking on "File" -> "Save As..." and let's name your script "R_Lesson2.R"  Click "Save".
Congratulations!  You've completed Lesson 2!

DOWNLOAD CODE Here is the code from my GitHub gist "R Lesson 2 - R-Studio Working Directory & File Operations" in case you'd rather just copy and paste it and then play around with it.

Tuesday, September 4, 2018

Lesson 1: Writing Your First Program In R Using R-Studio

So, you're ready to write your first program in R!  I'm really excited for you!  R is my one of my favorite programming languages because once you get the hang of the syntax, it's very intuitive and very well supported by the community.  Many times answers to your questions can be found through a simple Google search or by visiting Stack Exchange.

As you may (or may not) know when first learning a programming language, the first program you typically write is "Hello, World!".  So, that is what we are going to do here next with R in R-Studio!

NOTE:  To run the code in R-Studio, you can put your cursor all the way to the left on the line of code you'd like to execute.  For example place your cursor to the left of the 'p' in the 'print' function and press "ctrl + enter" (Windows/Linux) or "command + enter" (Mac OSX).  This will run that line of code and display "Hello, World!" in the R-Studio console window.


STEP 1: USE PRINT FUNCTION TO DISPLAY A STRING

To display a text string variable in the R-Studio console, you can use the 'print' function.
print("Hello, World!")

STEP 2: ASSIGN A STRING TO A VARIABLE AND USE PRINT TO DISPLAY IT

Next, let's assign "Hello, World!" to a string variable and use the 'print' function to display it in the console.
x = "Hello, World!"
print(x)

STEP 3: ASSIGN TWO STRINGS TO TWO VARIABLES AND USE PASTE TO DISPLAY IT

Next we will use the 'paste' function to combine variables and strings and like print, it will display the result in the console.

x = "Hello, World"
y = "once again!"
paste(x,y, sep = " ")

STEP 4: LEARNING MORE ABOUT R FUNCTIONS

At any time during your R-Studio session you can display information about a given functions by preceding the function with a '?'. This will display helpful information about the function in the viewer on the right.
?print
?paste

STEP 5: SAVING YOUR SCRIPT

Only one more step.  Let's save that script you just created by clicking on "File" -> "Save As..." and let's name your script "R_Lesson1.R"  Click "Save".
Congratulations!  You've completed Lesson 1!

DOWNLOAD CODE
Here is the code from my GitHub gist "R Lesson 1 - First Program" in case you'd rather just copy and paste it and then play around with it.