线性回归 - 将预测值附加到相同数据集

时间:2017-05-30 13:47:27

标签: r lm predict

我最近开始使用R编程。这是我的数据集

WeekOfYear  Production
         1      202612
         2      245633
         3      299653
         4      252612
         5      299633
         6      288993
         7      254653
         8      288612
         9      277733
        10      245633

我需要预测剩余的一周中的“生产”值

relation<-lm(Production~WeekOfYear,dataset)

predict(relation,data.frame(WeekOfYear=c(11)))

如何将第11周至第52周(年末)的预测值附加到同一数据集中,如下所示

WeekOfYear  Production
        1       202612
        2       245633
        3       299653
        4       252612
        5       299633
        6       288993
        7       254653
        8       288612
        9       277733
       10       245633
       11   predicted value
       12   predicted value

等等

-OR-

WeekOfYear  Production  Regression
         1      202612  fitted value
         2      245633  fitted value
         3      299653  fitted value
         4      252612  fitted value
         5      299633  fitted value
         6      288993  fitted value
         7      254653  fitted value
         8      288612  fitted value
         9      277733  fitted value
        10      245633  fitted value
        11              predicted value
        12              predicted value
        13              predicted value
        14              predicted value
         .
         .
        52              predicted value

2 个答案:

答案 0 :(得分:2)

要附加您的值,您可以使用以下

test_data <- data.frame(WeekOfYear=11:52, Production = rep(0, 52-11+1))
test_data$Production <- predict(relation,test_data)

df = rbind(df, test_data)

我已使用df数据框定义了

df = data.frame(WeekOfYear =
c(1,2,3,4,5,6,7,8,9,10),
Production = c(202612,245633,299653,252612,299633,288993,254653,288612, 277733,245633))

这会给你这种行为(情节拼凑得非常快)

enter image description here

我不确定您的数据是否符合线性行为,但您可能更了解您的数据......

答案 1 :(得分:2)

你可以这样做:

private void DGrdDatosImportar_Drop(object sender, RoutedEventArgs e)
{
    ...
    ScrollViewer sv = GetChildOfType<ScrollViewer>(DGrdDatosImportar);
    if (sv != null)
    {
        double horizontalOffset = sv.HorizontalOffset;
        //...
    }
}

private static T GetChildOfType<T>(DependencyObject depObj) where T : DependencyObject
{
    if (depObj == null)
        return null;

    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
    {
        var child = VisualTreeHelper.GetChild(depObj, i);

        var result = (child as T) ?? GetChildOfType<T>(child);
        if (result != null)
            return result;
    }
    return null;
}

结果:

relation <- lm(Production ~ WeekOfYear, dat)

WeekOfYear <- 1:52
predict(relation, data.frame(WeekOfYear))

dat2 <- data.frame(WeekOfYear, regression = predict(relation, data.frame(WeekOfYear)))

merge(dat, dat2, by = 'WeekOfYear', all.y = TRUE)