Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In R, how to add the fitted value column to the original dataframe?

Tags:

r

regression

I have a multiple regression model. I want to add the fitted values and residuals to the original data.frame as two new columns. How can I achieve that? My model in R is like this:

BD_lm <- lm(y ~ x1+x2+x3+x4+x5+x6, data=BD)
summary(BD)

I also got the fitted value

BD_fit<-fitted(BD_lm)

But I want to add this BD_fit values as a column to my original data BD. I don't know how. When I tried to call BD_fit, it just gave me a lot of numbers. I am running a large dataset, so it is hard to list all of them here.

like image 949
titi Avatar asked Sep 28 '13 09:09

titi


People also ask

How do I add data to an existing data in R?

To add or insert observation/row to an existing Data Frame in R, we use rbind() function. We can add single or multiple observations/rows to a Data Frame in R using rbind() function.

How do I add values to a row in a Dataframe in R?

Use add_row() from tibble or tidyverse The packages tibble or tidyverse provides a function add_row() to add a row to DataFrame in R. This is a convenient way to add one or more rows of data to an existing data frame.


1 Answers

Suppose:

fm <- lm(demand ~ Time, BOD)

Then try this:

cbind(BOD, resid = resid(fm), fitted = fitted(fm))

or this:

BOD$resid <- resid(fm)
BOD$fitted <- fitted(fm)

ADDED:

If you have NA values in demand then your fitted values and residuals will be of a different length than the number of rows of your data, meaning the above will not work. In such a case use: na.exclude like this:

BOD$demand[3] <- NA # set up test data
fm <- lm(demand ~ Time, BOD, na.action = na.exclude)

na.exclude will automatically pad the predictions and residuals with NA values so that they are of the same length as the original data. Now the previous lines should work.

like image 85
G. Grothendieck Avatar answered Oct 22 '22 09:10

G. Grothendieck