R Locfit包如何计算残差

时间:2016-07-11 04:44:02

标签: r regression

我使用locfit回归使用以下数据,并且对如何计算残差感到困惑。

http://pastebin.com/2iLaSxQD将其存储为station.means(我将文本文件称为January_raw_means.txt)

a: 12
b: 25
c: 41

我使用此代码调用locfit:

b <- read.table("./January_raw_means.txt", sep = "", header = TRUE)
station.means <- apply(b, 2, as.numeric) 
# Above is to store it as it is found within the original code.

然后使用以下方法调用残差:

locfit.regression <-   locfit(SD ~ Tmean + Elevation + Longitude + Latitude, 
                                 alpha = 0.3, 
                                 data = data.frame(station.means), maxk = 150)

第一站(数据中的行)的值为:

locfit.residuals <- residuals(locfit.regression)

但是,拟合值是

> locfit.residuals[1]
[1] 2.529492

但观察到的值是:

> fitted(locfit.regression, type = "fit")[1]
[1] 18.68174

造成这种差异的原因是什么?我尝试找到一个观察值,该值对应于从残差+拟合计算的值,但没有骰子。甚至尝试在四舍五入的情况下改变最后几位数。

> station.means[1, "SD"]
[1] 26.62326

发生了什么事?

2 个答案:

答案 0 :(得分:0)

(我知道这可以说是一个评论,但是通过&#34;回答编辑&#34;来提高清晰度。)当我下载数据并运行代码时,我得到了这个:

> locfit.residuals[1]
[1] -0.137262
> fitted(locfit.regression, type = "fit")[1]
[1] 26.76052
> station.means[1, "SD"]
      SD 
26.62326 
> station.means[1, "SD"]-fitted(locfit.regression, type = "fit")[1]
       SD 
-0.137262 

因此,当前版本的R和兼容版本的locfit确实没有差异:

> require(locfit)
Loading required package: locfit
locfit 1.5-9.1   2013-03-22

我上面的评论提出了一个似是而非的假设(第1行中缺少值)在较大的数据集中可能会出现这种情况。它可以通过以下方式进行测试:

station.means[ complete.cases(station.means), "SD"][1] - fitted(locfit.regression, type = "fit")[1]

complete.cases函数返回一个逻辑向量,只要数据帧中的行数等适合作为i中的选择向量 - &#34; [&#34] ;。所以我最好猜测这个问题与&#34;&#34;&#34;计算残差,而不是&#34;其中&#34;残差实际上就在那里。

答案 1 :(得分:0)

42-posted是正确的,事实上当我运行该代码时,我得到了正确的答案。但是,我在一年中的每个月使用for循环运行locfit呼叫(其中station.means是12个项目的列表,所以station.means [[1]]等)问题是locfit调用转到data.frame(station.means [[i]]),我正在进行for循环。这似乎不是以前的问题,包中没有错误。

public static dynamic DecodeJson(this string str)
{
    var serializer = new JavaScriptSerializer();
    serializer.MaxJsonLength = Int.MaxValue; // The value of this constant is 2,147,483,647
    serializer.RegisterConverters(new[] { new DynamicJsonConverter() });
    dynamic result = null;
    try
    {
        result = serializer.Deserialize(str, typeof(object));
    } catch (ArgumentException ae)
    {
        Log.Output(ae.InnerException.Message);
    }
    return result;
}

所以打电话给locfit会给..

print p.lower().count("h")

因此问题得到解决,因为locfit调用实际上是第i个元素。

使用lapply时会出现同样的问题。

locfit.regression <- vector(mode = "list", length = length(station.means))
for(i in 1:length(locfit.regression)) {
  locfit.regression[[i]] <-   locfit(SD ~ Tmean + Elevation + Longitude + Latitude, 
                                 alpha = 0.3, 
                                 data = data.frame(station.means[[i]]), maxk = 400)
}
locfit.residuals <- lapply(locfit.regression, residuals)
相关问题