# Ordinary Least Squares (OLS) with RLink

I need to calculate the parameters b0, b1 and b2 in:

y = b0 + b1 x1 + b2 x2


by Ordinary Least Squares (OLS).

The data in a CSV file is:

{{"x1", "x2", "y"}, {0, 2, 1}, {1, 5, 0}, {3, 3, 2}, {5, 9, 4}, {3, 4, 5}, {7, 10, 7}}


In R the process is:

info <- read.csv("C:\\Users\\Adminu\\Desktop\\prueba.csv", header = TRUE)

reg <- lm(y ~ x1+x2, data = info)

summary(reg)


In Mathematica I have executed:

REvaluate["lm(formula=y~x1+x2,data=info)"]


I get an error:

Failed to retrieve the value for variable or piece of code lm(formula=y~x1+x2,data=info). The following R error was encountered: Error in is.data.frame(data) : object 'info' not found

As the error says, the variable info that you are referring to does not exist in the R workspace. What you need to do is transfer the data from Mathematica to R.

One way is to create the variables x1, x2 and y in R using RSet

data = {{"x1", "x2", "y"}, {0, 2, 1}, {1, 5, 0}, {3, 3, 2}, {5, 9, 4}, {3, 4, 5}, {7, 10, 7}};

RSet[First[#], Rest[#]] & /@ Transpose[data]


Now you can run

REvaluate["{ reg <- lm(formula=y~x1+x2); reg\$coefficients }"]
(* RObject[{0.850746, 1.22388, -0.283582}, RAttributes["names" :> {"(Intercept)", "x1", "x2"}]] *)