====== Calculate R Expression ====== ===== Description ===== The functor 'Calculate R Expression' allows Dinamica EGO to call R externally and process the script outputs as if they were part of Dinamica itself. For an overview of how Dinamica and R can be linked together check the documentation about [[reference_book:r_coupling|R Coupling]]. ===== Inputs ===== ^ Name ^ Type ^ Description ^ | Expression | [[String Type]] | The expression that will run on R. | | Treat Warning As Errors | [[Boolean Value Type]] | Warnings on R script will be considered errors. | ===== Optional Inputs ===== None. ===== Output ===== ^ Name ^ Type ^ Description ^ | result | [[Struct Type]] | A struct containing the output values generated by the expression. | ===== Group ===== [[Functor List#Integration | Integration]] ===== Notes ===== There are two ways to setup the 'Calculate R Expression' functor: ==== Dinamica EGO Enhancement Plugin ==== Simply download and install the [[plugins_4|Dinamica EGO Enhancement Plugin]]. It contains everything you need to run R scripts inside Dinamica EGO. ==== Local R Installation ==== Additionally, users can specify and use their own local R installation for execution. The pre-requisites are: * R needs to be at least at the 3.3.1 version. * ''Rscript.exe'' must be valid and located at the ''/bin'' sub-folder. * [[external communication|Dinamica package]] for R must be installed and at the latest version. To specify your custom R installation, go to Tools --> Options --> Integration tab and select //Use alternative R installation for Calculate R Expression//: {{:dinamica_options_use_alternative_r_install.png?nolink|}} ---- ===== Usage ===== The functor is available under the //Integration// tab at the library. ===== R Script Inputs ===== To pass input parameters from Dinamica EGO to R, hooks must be placed to collect data. You can use the //Create a hook// button on the selected functor bar or drag the hooks individually. The valid hook types are: * [[Number Table]] * [[Number Value]] * [[Number String]] To access the passed inputs on your R script, follow Dinamica EGO naming conventions and use ''t[0-99]'', ''v[0-99]'', ''s[0-99]'' for each type respectively. For example: # Will store the 5th key from the passed Lookup Table in the variable 'testing' testing <- t1$Keys[ 5 ]; # Store the second passed String. secondString <- s2; # Store the 10th passed Value. tempNumber <- v10; ===== R Script Outputs ===== To output data back to Dinamica EGO, the user must call a set of functions designed for this functionality: ^ Function name ^ Output Data Type ^ Usage Example ^ | outputDouble() | Real | outputDouble( "myDouble", 3.14 ) | | outputNumberVector() | Tuple | outputNumberVector( "myTuple", c(1:10) ) | | outputString() | String | outputString( "myString", "This is a string" ) | | outputLookupTable() | LookupTable | outputLookupTable( "myLUT", c(1:10), c(1:10) * 10 ) | | outputTable() | Table | outputTable( "myTable", data.frame(State = c("Massachusetts", "Massachusetts"), City = c("Boston", "Chelsea"), Population = c(667137, 39398), stringsAsFactors = FALSE), 2 ) | In the examples above, data was constructed inside the calling functions. You can also specify variables as parameters. All output functions require an identifier as the first parameter, that's the name Dinamica uses for retrieving the correct data (to put into the struct output). Keep in mind: * You can pass any kind of numeric value on the ''outputDouble'' function. * Collections of numbers are valid number vector's. * A [[Lookup Table Type|Lookup Table]] requires //2// number vectors, one for the "Key" and another for the "Value". Both vectors must have the same number of elements. * The ''outputTable'' function requires a table, that can be constructed with [[http://www.r-tutor.com/r-introduction/data-frame | data.frame]] R function. There is another parameter that is optional with default value 1, and it means how many Key columns the table has, from the leftmost column. Notice the use of the stringAsFactors = FALSE flag. This flag prevents R from converting the passed strings to Factors(numbers). ==== Tables / Lookup Tables ==== [[Table Type|Tables]] or [[Lookup Table Type|Lookup Tables]] can be transferred to R using the [[Number Table]] functor. When dealing with each of these types extra caution must be taken: === Lookup Tables === Lookup Tables are transferred to R as a List with two columns, "Key" and "Value". Each column can be individually accessed by using the ''$'' operator, for example: * ''t1$Key[ 1 ]'' will access the first key of the Lookup Table ''t1''. * ''t2$Value[ 2 ]'' will access the second value of the Lookup Table ''t2'' === Tables === Tables are transferred to R as a [[https://en.wikibooks.org/wiki/R_Programming/Working_with_data_frames|DataFrame]] type variable. Each column can be individually accessed by using the ''$'' operator, just like Lookup Tables. Please check [[external_communication#table|this page]] for more information on how to deal with Tables. The rules for them in [[Calculate R Expression]] are the same as sending and receiving through [[External Communication]]. ===== Example Scripts ===== ==== Multiply each value of the passed Lookup Table by itself ==== {{ ::ex1_calculate_r.png?nolink |}} Expression: for ( i in 1:length( t1$Value ) ) { tempValue <- t1$Value[ i ]; t1$Value[ i ] = tempValue * tempValue; } outputLookupTable( "poweredTable", t1$Key, t1$Value ); ==== Extract the mean of passed Lookup Table values ==== {{ ::ex2_calculate_r.png?nolink |}} Expression: tableMean <- mean( t1$Value ); print( paste( "Mean is", tableMean ) ); outputDouble( "mean", tableMean ); Noticed the ''print()'' statement? Dinamica EGO's Message Log will show output messages from the R script (as Result's).If the Message Log level is Unconditional, the messages will not be printed. ==== Plot passed Lookup Table to an image on the path specified by passed String ==== {{ ::ex3_calculate_r.png?nolink |}} Expression: outputFile <- s1; print( paste( "Plotting to", outputFile ) ); jpeg( outputFile, quality=100 ); plot( t1 ); dev.off(); ===== Internal Name ===== CalculateRExpression