In R, doing linear regression

Viewed 49

I am testing manually doing linear regression, step by step. In the equation:

y = a1 + a2 * x

I am not successful making R compute y beyond first x value. Below are my codes:

library(tidyverse)
library(modelr)

# training dataset
train_data <- sim1

str(sim1)
tibble [30 × 2] (S3: tbl_df/tbl/data.frame)
$ x: int [1:30] 1 1 1 2 2 2 3 3 3 4 ...
$ y: num [1:30] 4.2 7.51 2.13 8.99 10.24 ...

# equations dataset
equation_data <- tibble(
  a1 = runif(250, min = -20, max = 40),
  a2 = runif(250, min = -5, max = 5)
)

str(equation_data)
tibble [250 × 2] (S3: tbl_df/tbl/data.frame)
$ a1: num [1:250] 32.81 33.11 9.97 -18.64 30.32 ...
$ a2: num [1:250] -4.9 1.23 -4.11 -3.01 4.74 ...

# function to predict y from equation data
predict_y <- function(param, train){
  param[1] + param[2] * train$x
}

predict_y(as.vector(equation_data[1,]), train_data)
$     a1
$1 27.90916

As you can see, R is computing only the first x value:

y = a1 + a2 * x

27.909 = 32.81 + (-4.9) * 1

What do I do to make R produce a vector of 30 y values, using all 30 x values?

Thanks!

1 Answers

try the following. You need to use as.numeric to convert each row of equation_data to a vector. I didn't have your sim1 dataframe. So I created one.

library(tidyverse)
library(modelr)

# training dataset
train_data <- data.frame(x = c(1, 1, 1, 2, 2),
                         y = c(4.2, 7.51, 2.13, 8.99, 10.24))

# equations dataset
equation_data <- tibble(
  a1 = runif(250, min = -20, max = 40),
  a2 = runif(250, min = -5, max = 5)
)

# function to predict y from equation data
predict_y <- function(param, train){
  param[1] + param[2] * train$x
}

predict_y(as.numeric(equation_data[1,]), train_data)

Related