2016-09-01 18 views
0

我試圖使用分段迴歸進行預測,它給了我一個錯誤:「eval(expr,envir,enclos):object'U1.Sepal.Width'not found」中的錯誤。我究竟做錯了什麼?Error.segmented中的錯誤

下面是示例代碼:

library("segmented") 
    data("iris") 
    breaks <- list(Sepal.Width = quantile(iris$Sepal.Width, c(0.25, 0.5, 0.75)), 
        Petal.Width = quantile(iris$Petal.Width, c(0.25, 0.5, 0.75))) 
    fit.lm <- lm(Sepal.Length ~ Sepal.Width + Petal.Width, data = iris) 
    fit.segmented <- segmented(fit.lm, seg.Z = ~ Sepal.Width + Petal.Width, 
           psi = breaks, control = seg.control(it.max = 0)) 
    summary(fit.segmented) 
# 
# Call: 
# lm(formula = Sepal.Length ~ Sepal.Width + Petal.Width + U1.Sepal.Width + 
#  U2.Sepal.Width + U3.Sepal.Width + U1.Petal.Width + U2.Petal.Width + 
#  U3.Petal.Width, data = mfExt) 
# 
# Residuals: 
# Min  1Q Median  3Q  Max 
# -1.25915 -0.25375 -0.02634 0.22621 1.25034 
# 
# Coefficients: 
# Estimate Std. Error t value Pr(>|t|)  
# (Intercept)  3.3287  0.8546 3.895 0.000151 *** 
# Sepal.Width  0.4309  0.3066 1.405 0.162120  
# Petal.Width  0.2362  1.0925 0.216 0.829120  
# U1.Sepal.Width 0.4492  0.8220 0.546 0.585606  
# U2.Sepal.Width -0.7730  0.9027 -0.856 0.393306  
# U3.Sepal.Width 0.8078  0.6080 1.329 0.186139  
# U1.Petal.Width 1.1081  1.2094 0.916 0.361099  
# U2.Petal.Width -0.4990  0.3862 -1.292 0.198400  
# U3.Petal.Width -0.4617  0.4824 -0.957 0.340195  
# --- 
# Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 
# 
# Residual standard error: 0.4381 on 141 degrees of freedom 
# Multiple R-squared: 0.7351, Adjusted R-squared: 0.72 
# F-statistic: 48.9 on 8 and 141 DF, p-value: < 2.2e-16   

    predict(fit.segmented, data.frame("Sepal.Width" = 3, "Petal.Width" = 1.8), se.fit = TRUE) 
#Error in eval(expr, envir, enclos) : object 'U1.Sepal.Width' not found 

回答

0

你似乎需要建立在「newdata」對象用手U1.xx列。

(這似乎很奇怪行爲要求)

但是,你能夠做到這一點,你可以使用切:

# new data 
newD <- data.frame("Sepal.Width" = 3, "Petal.Width" = 1.8) 
# function to get breaks 
toBr <- function(name, breaks, values){ cut(values, c(-Inf,breaks,Inf), sprintf("U%s.%s",seq_len(length(breaks)+1)-1,name))} 

# use nnet::class.ind to convert from factor to indicator matrix 
# don't really need U0.xxx but no harm keeping 
list_results <- lapply(Map(toBr, names(newD), breaks, newD), nnet::class.ind) 
# combine with newD and then predict) 
predict(fit.segmented,cbind(newD,do.call(cbind, list_results))) 
+0

不幸的是,你的代碼所提供的回報不同的擬合值(相比那些由'fit.segmented $ fitted'返回)。 – user4968068