0

我使用来自 ACS 的县数据在 R 中创建了一个线性模型。我的数据集中有 3140 个条目,它们都有对应的 fips 代码。我正在尝试从我的线性模型中制作残差图,但我只有 3139 个残差。有谁知道在创建负责此问题的线性模型时 R 是否会执行某些操作,以及如何修复它以便创建此地图?谢谢!

为了响应检查 NAs 的建议,我运行了这个:

which(completedata$fipscode == NA)
integer(0)

R代码如果有帮助:

sectorcodes <- read.csv("sectorcodes1.csv") #ruralubrancode, median hh income
sectorcodesdf <- data.frame(sectorcodes)
religion <- read.csv("Religion2.csv")
religiondf <- data.frame(religion)

merge1 <- merge(sectorcodesdf,religiondf, by = c('fipscode'))
merge1df <- data.frame(merge1)

family <- read.csv("censusdataavgfamsize.csv") #avgfamilysize
familydf <- data.frame(family)

merge2 <- merge(merge1df, familydf, by = c('fipscode'))
merge2df <- data.frame(merge2)

gradrate <- read.csv("censusdatahsgrad.csv")
gradratedf <- data.frame(gradrate)
evenmoredata2 <- merge(gradrate,merge2df, by=c("fipscode"))

#write.csv(evenmoredata2, file = "completedataset.csv")
completedata <- read.csv("completedataset.csv")
completedatadf <- data.frame(completedata)

lm8 <- lm(completedatadf$hsgrad ~ completedatadf$averagefamilysize*completedatadf$Rural_urban_continuum_code_2013*completedatadf$TOTADH*completedatadf$Median_Household_Income_2016)
summary(lm8)

library(blscrapeR)
library(RgoogleMaps)
library(choroplethr)
library(acs)
attach(acs)
require(choroplethr)

dataframe1 <- data.frame(completedatadf$fipscode,completedatadf$averagefamilysize)
names(dataframe1) <- c("region","value")

dataframe2 <- data.frame(completedata$fipscode,completedata$hsgrad)
names(dataframe2) <- c("region","value")

residdf <- data.frame(lm8$residuals)
dataframe3 <- data.frame(completedata$fipscode,lm8$residuals)
names(dataframe3) <- c("region","value")
county_choropleth(dataframe1)
county_choropleth(dataframe2)
county_choropleth(dataframe3)

当我尝试运行 dataframe3 时,错误消息是:

dataframe3 <- data.frame(completedata$fipscode,lm8$residuals)
Error in data.frame(completedata$fipscode, lm8$residuals) : 
arguments imply differing number of rows: 3140, 3139
4

2 回答 2

1

这可能是由响应中的 NA 引起的。例如,使用内置BOD数据框请注意,此示例中有 5 个残差,但 6 行b

b <- BOD
b[3, 2] <- NA
nrow(b)
## [1] 6
fm <- lm(demand ~ Time, b)
resid(fm)
##          1          2          4          5          6 
## -0.3578947 -0.2657895  1.6184211 -0.6894737 -0.3052632 

我们可以通过指定na.action = na.exclude何时运行来处理它lm。请注意,现在有 6 个残差,额外的一个为 NA。

fm <- lm(demand ~ Time, b, na.action = na.exclude)
resid(fm)
##          1          2          3          4          5          6 
## -0.3578947 -0.2657895         NA  1.6184211 -0.6894737 -0.3052632 
于 2018-05-07T18:19:57.503 回答
0

尝试

data.frame(na.omit(completedata$fipscode), lm8$residuals) 

可能,您的数据具有NA价值。

于 2018-05-07T18:14:21.393 回答