MicroStrategy ONE

The R Integration Pack is no longer supported as of December 2024.

Combining All Techniques for a Robust Script

The simple R script example, unmodified, is shown below.

Copy
# Create a data frame from the input variables
df <data.frame(cbind(Target, Trend, Season))
# Train model on all records with Target values
model <- lm(Target ~ Trend + factor(Season),data=df[!is.na(Target), ])
# Return predictions from the model
Forecast <predict(model, newdata = df[, -1])

By using all of the recommendations above, the script shown below is more robust to handle errors, generates PMML, saves important objects from the R environment for future analysis, and can be executed using the R console or MicroStrategy:

Copy
# tryCatch for Exception Handling
mstr.ErrMsg <tryCatch({

#Working Directory if executed by MicroStrategy
if (exists("mstr.WorkingDir")) setwd(mstr.WorkingDir)

# Check to see if package(s) are installed, install if not and then load
# pkgs is a vector of strings with length >=1
CheckInstallPackages <function(pkgs){
# For each pkg in pkgs (attempt to load each package one at a time):
x <- lapply(pkgs, function(pkg){
# Load the package if available,
if (!do.call("require", list(pkg))) {
# Silently attempt to install into the default library
try(install.packages(pkg,lib=.Library,repos="http://cran.rstudio.com"))
# Now attempt to load the package, catch error if it wasn't installed
tryCatch(do.call("library", list(pkg)),
# Catch if we're unable to install into the default library
error = function(err) {
# If non-interactive, install into this user's personal library
if(!interactive()) {
# Get the path to this user's personal library
personalLibPath <-Sys.getenv("R_LIBS_USER")
# If the personal library is not in the list of libraries
if (is.na(match(personalLibPath, .libPaths()))) {
# Then create the personal library
dir.create(personalLibPath, recursive = TRUE)
# And add the personal library to the list of libraries.
libPaths(personalLibPath)

# Attempt to install the package into the personal library
# If this fails, raise the error back to the report
install.packages(pkg, lib=personalLibPath, repos="http://cran.rstudio.com")
# Finally, attempt to load the package
do.call("library", list(pkg))
}})}})
}

# Get data
# If this is executed by MicroStrategy
if (exists("mstr.ExFlag")) {
# Create a data frame from the input variables
df <data.frame(cbind(Target, Trend, Season))
# If InputNames is non-empty
if (length(mstr.InputNames) > 0) {
# Name these variables
colnames(df) <- mstr.InputNames
}
# If this is NOT via a MicroStrategy Report Execution
} else {
# Set random number seed for consistency
set.seed(42)
# Set Trend variable for 48 months
Trend <seq(1:48)
# Set Season variable for 4 years of 12 months
Season <rep(seq(1:12),4)
# Set 3 years of linear but noisy values for the Target
Target <- (seq(1:36)*(0.8+(0.4*runif(36,0,1))))
# Add the forecast horizon
Target <append(Target, c(rep(NA, 12)))
# Create a data frame from the input variables
df <data.frame(cbind(Target, Trend, Season))
# Set the name for saving output
FileName <"SeasonalForecasting_console"
}

# Modeling
# Train model on all records with Target values
model <- lm(Target ~ Trend + factor(Season),data=df[!is.na(Target), ])
# Return predictions from the model
Forecast <predict(model, newdata = df[, -1])

# If FileName is not an empty string
if (nchar(FileName)>0) {
# Persist objects to file
save(list=c("df", "model", "Forecast"), file=paste(FileName,".Rdata", sep = ""))
# Load the PMML package
CheckInstallPackages(c("pmml"))
# Save the model as PMML
saveXML(pmml(model), paste(FileName,".xml", sep=""))
}

# Print completion message when run from the console
try(print("Success!"))
# If we made it here, no errors were caught
mstr.ErrMsg <""
# Catch block to report an error
}, error = function(err) {
# Print error message if run from console try(print(err))
# Return error message
return(err$message)
})