【发布时间】:2014-12-16 00:05:38
【问题描述】:
我正在尝试对数据框中的数据组(县)进行回归 (lm)。但是,我首先要过滤该数据框(dat)以排除一些数据点太少的组。只要我不先对数据框进行子集化,我就能让一切正常工作:
tmp1 <- with(dat,
by(dat, County,
function(x) lm(formula = Y ~ A + B + C, data=x)))
sapply(tmp1, function(x) summary(x)$adj.r.squared)
我按预期回来了:
巴罗卡罗尔切诺基克莱顿科布德卡尔布道格拉斯
0.00000 NaN 0.61952 0.69591 0.48092 0.61292 0.39335
但是,当我第一次对数据框进行子集化时:
dat.counties <- aggregate(dat[,"County"], by=list(County), FUN=length)
good.counties <- as.matrix(subset(dat.counties, x > 20, select=Group.1))
dat.temp <- dat["County" %in% good.counties,]
然后运行相同的代码:
tmp2 <- with(dat,
by(dat, County,
function(x) lm(formula = Y ~ A + B + C, data=x)))
sapply(tmp2, function(x) summary(x)$adj.r.squared)
我收到以下错误:“$ 运算符对原子向量无效”。如果我然后运行
summary(tmp2)我看到以下内容:
Length Class ModeBarrow 0 -none- NULL
卡罗尔 0 -none- NULL
切诺基 12 lm 列表
克莱顿 12 lm 列表
sapply 显然正在轰炸 Class -none- 对象。但那些是我上面排除的那些!它们怎么还出现在我的新数据框中?!
感谢您的任何启发。
【问题讨论】:
-
请提出您的问题reproducible。当您这样做时,提供帮助会容易得多。请注意,您在第二个代码段中使用了错误的
dat(应该是dat.temp),但我认为这不是问题所在。