【问题标题】:Error in R Subsetting data frame and then using sapplyR 子集数据帧中的错误,然后使用 sapply
【发布时间】: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  Mode

Barrow 0 -none- NULL

卡罗尔 0 -none- NULL

切诺基 12 lm 列表

克莱顿 12 lm 列表

sapply 显然正在轰炸 Class -none- 对象。但那些是我上面排除的那些!它们怎么还出现在我的新数据框中?!

感谢您的任何启发。

【问题讨论】:

  • 请提出您的问题reproducible。当您这样做时,提供帮助会容易得多。请注意,您在第二个代码段中使用了错误的 dat(应该是 dat.temp),但我认为这不是问题所在。

标签: r subset sapply


【解决方案1】:

部分代码不清楚。可能是你做了attach 数据集。此外,正如@BrodieG 所评论的那样,存在使用错误的dat 而不是dat.temp 的问题。关于错误,可能是因为 County 列是 factor 并且 levels 没有被删除。你可以试试

dat.temp1 <- droplevels(dat.temp)
tmp2 <- with(dat.temp1, 
      by(dat.temp1, County,
      function(x) lm(formula = Y ~ A + B + C, data=x)))
sapply(tmp2, function(x) summary(x)$adj.r.squared)

这是一个重现错误的示例

set.seed(24)
d <- data.frame(
 state = rep(c('NY', 'CA','MD', 'ND'), c(10,10,6,7)),
 year = sample(1:10,33,replace=TRUE),
 response= rnorm(33)
)

 tmp1 <- with(d, by(d, state, function(x) lm(formula=response~year, data=x)))
 sapply(tmp1, function(x) summary(x)$adj.r.squared)
 #       CA          MD          ND          NY 
 # 0.03701114 -0.04988296 -0.07817515 -0.11850038 

d.states <- aggregate(d[,"state"], by=list(d[,'state']), FUN=length)
good.states <- as.matrix(subset(d.states, x > 6, select=Group.1))
d.sub <-  d[d$state %in% good.states[,1],]

tmp2 <- with(d.sub, 
    by(d.sub, state,
      function(x) lm(formula = response~year, data=x)))
sapply(tmp2, function(x) summary(x)$adj.r.squared)
#Error in summary(x)$adj.r.squared : 
# $ operator is invalid for atomic vectors

如果你看

 tmp2[2]
 #$MD
 #NULL

d.sub1 <- droplevels(d.sub)
tmp2 <- with(d.sub1, 
      by(d.sub1, state,
          function(x) lm(formula = response~year, data=x)))
sapply(tmp2, function(x) summary(x)$adj.r.squared)
#       CA          ND          NY 
# 0.03701114 -0.07817515 -0.11850038 

【讨论】:

  • 谢谢阿克伦。 droplevels 做到了。我之前确实附加了 dat 数据集,但后来我将其分离,并认为这会使一切恢复原状。是的,对于@BrodieG 指出的错误“dat.temp”感到抱歉。
猜你喜欢
  • 1970-01-01
  • 2015-08-22
  • 1970-01-01
  • 1970-01-01
  • 2016-03-08
  • 1970-01-01
  • 2017-08-12
  • 2018-04-18
  • 1970-01-01
相关资源
最近更新 更多