Does anyone know how to solve the attached problem in two lines of code? I believe an as.matrix would work to create a matrix, X, and then use X %*% X, t(X), and solve(X) to get the answer. However, it does not seem to be working. Any answers will help, thanks. 
            Asked
            
        
        
            Active
            
        
            Viewed 56 times
        
    -3
            
            
        - 
                    1Please show us what you've tried so far. It would be helpful for you to produce a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – Kevin Arseneau Oct 04 '17 at 23:42
2 Answers
1
            
            
        I would recommend using read.csv instead of read.table
It would be useful for you to go over the difference of the two functions in this thread: read.csv vs. read.table
df <- read.csv("http://pengstats.macssa.com/download/rcc/lmdata.csv")
model1 <- lm(y ~ x1 + x2, data = df)
coefficients(model1) # get the coefficients of your regression model1
summary(model1) # get the summary of model1 
 
    
    
        TechWizard
        
- 346
- 1
- 7
0
            
            
        Based on the answer of @kon_u, here is an example to do it by hands:
df <- read.csv("http://pengstats.macssa.com/download/rcc/lmdata.csv")
model1 <- lm(y ~ x1 + x2, data = df)
coefficients(model1) # get the coefficients of your regression model1
summary(model1) # get the summary of model1 
### Based on the formula
X <- cbind(1, df$x1, df$x2) # the column of 1 is to consider the intercept
Y <- df$y
bhat <- solve(t(X) %*% X) %*% t(X) %*% Y # coefficients 
bhat # Note that we got the same coefficients with the lm function
 
    
    
        nghauran
        
- 6,648
- 2
- 20
- 29
- 
                    Note that this formula allows you to compute coefficients of multivariate linear regressions too. – nghauran Oct 05 '17 at 15:39
