我是R的新手并尝试使用cv.lm进行K折交叉验证()参考:http://www.statmethods.net/stats/regression.html
我收到错误,表明我的变量长度不同.在我使用length()进行验证时,我发现其大小实际上是相同的.
以下是复制问题的最小数据集,
X Y 277 5.20 285 5.17 297 4.96 308 5.26 308 5.11 263 5.27 278 5.20 283 5.16 268 5.17 250 5.20 275 5.18 274 5.09 312 5.03 294 5.21 279 5.29 300 5.14 293 5.09 298 5.16 290 4.99 273 5.23 289 5.32 279 5.21 326 5.14 293 5.22 256 5.15 291 5.09 283 5.09 284 5.07 298 5.27 269 5.19
使用以下代码进行交叉验证
# K-fold cross-validation, with K=10 sampledata <- read.table("H:/sample.txt", header=TRUE) y.1 <- sampledata$Y x.1 <- sampledata$X fit=lm(y.1 ~ x.1) library(DAAG) cv.lm(df=sampledata, fit, m=10)
终端上的错误,
Error in model.frame.default(formula = form, data = df[rows.in, ], drop.unused.levels = TRUE) : variable lengths differ (found for 'x.1')
验证,
> length(x.1) [1] 30 > length(y.1) [1] 30
以上证实长度是相同的.
> str(x.1) int [1:30] 277 285 297 308 308 263 278 283 268 250 ... > str(y.1) num [1:30] 5.2 5.17 4.96 5.26 5.11 5.27 5.2 5.16 5.17 5.2 ... > is(y.1) [1] "numeric" "vector" > is(x.1) [1] "integer" "numeric" "vector" "data.frameRowLabels"
进一步检查上面的数据集表明一个数据集是整数,另一个是数字.但即使将数据集转换为整数或整数转换为数字,屏幕上也会弹出相同的错误,指示数据长度问题.
你能指导我怎么做才能纠正这个错误吗?
我从2天前开始处理这个问题是不成功的.我的研究使用互联网没有得到任何好的线索.
附加相关查询:
如果我们在属性中使用数据集的标题,我看到拟合有效,
fit=lm(Y ~ X, data=sampledata)
a)上述语法的区别是什么,
fit1=lm(sampledata$Y ~ sampledata$X)
以为它是一样的.在下面,
#fit 1 works fit1=lm(Y ~ X, data=sampledata) cv.lm(df=sampledata, fit1, m=10) #fit 2 does not work fit2=lm(sampledata$Y ~ sampledata$X) cv.lm(df=sampledata, fit2, m=10)
问题出在df = sampledata,因为标题" sampledata $ Y "不存在但只存在$ Y. 试图将cv.lm手动到下面它也不起作用,
cv.lm(fit2, m=10)
b)如果我们喜欢操纵变量,如何在cv.lm()中使用它,例如
y.1 <- (sampledata$Y/sampledata$X) x.1 <- (1/sampledata$X) #fit 4 problem fit4=lm(y.1 ~ x.1) cv.lm(df=sampledata, fit4, m=10)
有没有办法在函数中引用y.1和x.1而不是标题Y~X?
谢谢.