3 Replies Latest reply on Aug 26, 2016 3:28 PM by Bora Beran

    Correct format for Predict function in Tableau / R

    Matthew Petrich

      Hello,

      I have a data set with a dependent variable (return on investment) and six predictor variables.

      The six predictor variables correlate to the dependent variable and have a linear relationship.

       

      I want to use the Tableau / R integration to do a linear multiple regression with the six predictor variables to predict my dependent variable.

       

      I started with the R code below but I am not sure how to get to the predictive part.  The code below works and returns the results to my Tableau view.

      I am not sure how to add in the Predict code.

      The result I want to come back to Tableau is the predicted dependent variable and the six predictor variables that were used to make the prediction.

      This would be done for each row in the data set.

      Thank you for the help!

       

      SCRIPT_REAL( "

       

       

          ## Defining Variables

       

       

          cons <- .arg1

          crud <- .arg2

          djia <- .arg3

          fore <- .arg4

          gnp <- .arg5

          inte <- .arg6

          purc <- .arg7

       

       

          ## Fitting the Model

       

       

          fit <- lm( cons ~ crud + djia + fore + gnp + inte + purc )

          fit$fitted

      "

      , AVG( [Dependant Variable] ), AVG([MR Variable 1]), AVG([MR Variable 2]), AVG([MR Variable 3]),

      AVG([MR Variable 4]), AVG([MR Variable 5]), AVG([MR Variable 6]) )

       

      UPDATE

      I am now using this version of the R code.  This seems to be working but I have not verified the math yet.

      Does this look right?

      Thanks

       

      SCRIPT_REAL( "

       

       

          ## Defining Variables

       

       

          cons <- .arg1

          crud <- .arg2

          djia <- .arg3

          fore <- .arg4

          gnp <- .arg5

          inte <- .arg6

          purc <- .arg7

          predictors <- .arg2+.arg3+.arg4+.arg5+.arg6+.arg7

       

       

          ## Fitting the Model

          fit <- lm( cons ~ crud + djia + fore + gnp + inte + purc )   

          coeffs <- coefficients(fit) 

          prediction <- (coeffs[2] * predictors) + coeffs[1]

      "

      , AVG( [Dependant Variable] ), AVG([MR Variable 1]), AVG([MR Variable 2]), AVG([MR Variable 3]),

      AVG([MR Variable 4]), AVG([MR Variable 5]), AVG([MR Variable 6]) )

       

      Message was edited by: Matthew Petrich