Analytics Designer tips and tricks: Data Science Global scripts using the R widget
I’m inaugurating a blog series on tips and tricks in Analytics designer. Mostly, it is small things that application designers might find useful and helpful. As our first instalment, I show something that I’ve shown off in demos and in training material in the past, which has always gotten an enthusiastic response. You can
abuse use the R widget as a data science global script container.
How R works in SAP Analytics Cloud
When R was first included in SAP Analytics Cloud, it was intended to be a visualization tool; a way for end users to write their own charts. There is no built-in feedback mechanism for returning an R data frame to models or to other widgets.
1 -The data attached to the widget refreshes.
2 – The R script executes
3 – The results are passed to the R widget in the browser for rendering
4 – The onResultChanged script event is called and executes, if it is an app.
The r widget has another script method, getEnvironmentValues(). The object returned by this method has a getNumber() method. In case you have not made the connection yet, you can fish R variables out of the R runtime and use them in your script. You don’t even need to render anything using R and can leave the widget set to invisible in the styling pane. These two things together let you use R as a de-facto global data science script language in applications.
Take a look at the simple app below. It has a chart and a table, both displaying two measures; the Gross Margin actuals and the predicted (Plan) values. Let’s calculate the coefficient of correlation between them.
Let’s add a new text widget, Text_1, at the very top of the app. Let’s add a new R widget, RVisualization_1.
Set RVisualization_1 to use the same two measures as the table and a dimension, so that the R data frame is tabular. R’s corr function can’t calculate a coefficient of correlation between two numbers; it needs two lists of numbers, so we need a dimension. In the R script, enter a script that gets the two measures and calculated the coefficient of correlation.
grossMargin <- BestRun_Advanced$`Gross Margin` grossMarginPlan <- BestRun_Advanced$`Gross Margin Plan` delta_corr <- cor(grossMargin, grossMarginPlan)
In the onResultChanged() script event, add a script that gets delta_corr from the R environment, converts it to a string and applies it as the text in Text_1.
var computedCorrelation = this.getEnvironmentValues().getNumber('delta_corr'); var corrAsString = computedCorrelation.toString(); Text_1.applyText(corrAsString);
Now we can show the coefficient of correlation to the end user. Hopefully, this will fuel your creativity and you’ll come up with your own ways to enhance your apps using R.