Fit a LR model

R is good in the stat, bio side.

Note

Note that below is not fully developed.

Here are some examples of R codes:

Have all setups like loading library in one block of code

Code
# load library
library(tidyverse)

Calculating mean of a vector of length n

Code
n <- 10
x <- rnorm(n=n)
print(mean(x))
[1] -0.3907833

Fitting a simple linear regression model

Code
# create dummy data
n <- 25
x1 <- rnorm(n=n, mean=2, sd=3)
x2 <- rnorm(n=n, mean=3, sd=2)
y <- 2*x1 + 3*x2
data <- data.frame(x1 = x1, x2 = x2, y = y)

#> fit model and print fitted coefficients
reg <- lm(y ~ . , data=data)
print(reg$coefficients)
  (Intercept)            x1            x2 
-2.167242e-15  2.000000e+00  3.000000e+00 

Plot the model

Code
fit <- reg
p <- ggplot(fit$model, aes_string(x = names(fit$model)[2], y = names(fit$model)[1])) + 
  geom_point() +
  stat_smooth(method = "lm", col = "red") +
  labs(title = paste("Adj R2 = ",signif(summary(fit)$adj.r.squared, 5),
                     "Intercept =",signif(fit$coef[[1]],5 ),
                     " Slope =",signif(fit$coef[[2]], 5),
                     " P =",signif(summary(fit)$coef[2,4], 5)))

p

Figure 1: Simple Linear Regression on dummy data

The Figure 1 shows the fitted regression line on the dummy data