RyanB
RyanB

Reputation: 13

how to put my model's results into my dataframe?

I have a data set that's about 900 individual parts all with data going back 13 months. I want r to use linear regression to tell me how much of each part i should be stocking next month, using that 13 month rolling period that i have data for as my input.

datset description: I have about 900 rows and 13 filled in columns, with one column awaiting the results to be filled in. column 1 is the part number, followed by 13 columns of the previous months, last column is an empty column I labeled as "mlsuggestions"

Here is the code i'm currently using to do that:

    lmtest <- my.data

    set.seed(101)
    sample <- sample.split(lmtest$mlsuggestions, SplitRatio = 0.7)

    train <- subset(lmtest, sample == TRUE)
    test <- subset(lmtest, sample == FALSE)

    model1 <- lm(mlsuggestions ~ Dec_17 + Nov_17 + Oct_17 + Sept_17 +   
    Aug_17 + Jul_17 +   Jun_17 + May_17 +   Apr_17 + Mar_17 +   Feb_17 + 
    Jan_17 + Dec_16, data = lmtest)

    lmtest$mlsuggestions <- model1$coefficients

What i'm getting, from that very last line, is an error message that reads:

Error in `$<-.data.frame`(`*tmp*`, mlsuggestions, value = c(0, 0, 0, 0,  : 
 replacement has 14 rows, data has 886

So as I understand it, the model only has 14 coefficients to put in my 886 rows. Does that mean my model calculated by column and not by row? if that is the case, how do i change that?

and if that is not the case is there something wrong with the way i'm trying to put my model's results back into my data?

Upvotes: 0

Views: 605

Answers (1)

kangaroo_cliff
kangaroo_cliff

Reputation: 6222

I think what you are after implemented in the broom package. See if the outcome of the following is what you are after.

library(broom)
df <-  augment(model1)

For an example

model1 <- lm(Sepal.Length ~ ., iris)
library(broom)
df <- augment(model1)

df[1:5, ]

# Sepal.Length Sepal.Width Petal.Length Petal.Width Species  .fitted    .se.fit      .resid       .hat
#1          5.1         3.5          1.4         0.2  setosa 5.004788 0.04479188  0.09521198 0.02131150
#2          4.9         3.0          1.4         0.2  setosa 4.756844 0.05514933  0.14315645 0.03230694
#3          4.7         3.2          1.3         0.2  setosa 4.773097 0.04690495 -0.07309695 0.02336968
#4          4.6         3.1          1.5         0.2  setosa 4.889357 0.05135928 -0.28935683 0.02801904
#5          5.0         3.6          1.4         0.2  setosa 5.054377 0.04736842 -0.05437691 0.02383379
#     .sigma      .cooksd .std.resid
#1 0.3077918 0.0003570856  0.3136729
#2 0.3076565 0.0012517183  0.4742964
#3 0.3078349 0.0002317688 -0.2410693
#4 0.3069173 0.0043961179 -0.9565608
#5 0.3078627 0.0001309299 -0.1793744

Upvotes: 1

Related Questions