去除异常值线性回归

Removing outliers linear regression

我是 运行 通过线性回归和发现异常值的数据。我试过 data=dataframe[-c("country1", "country2"),] 但异常值仍然出现。我可以在这里得到一些帮助吗?谢谢

#Remove outliers
fit <- lm(Robbery ~ Unlawful.acts.involving.controlled.drugs.or.precursors, 
          data=NoNACountry[-c("Spain", "Luxembourg"),])
par(mfrow=c(2,2))
plot(fit)

我想我以某种方式丢失了行名称,因为我认为 RobberyUnlawful.acts... 已成为向量?我使用国家名称是行标签,RobberyUnlawful.acts... 是列。我已经能够通过这里的指导在其他代码中使用 drop = FALSE,但我无法在此处合并这种方法

Dataframe信息如下

structure(list(Intentional.homicide = c(2.03, 0.84, 1.14), Attempted.intentional.homicide = c(3.25, 
1.93, 0.54), Assault = c(5.52, 43.29, 39.54), Kidnapping = c(0.14, 
0.07, 1.03), Sexual.violence = c(5.38, 50.9, 8.64), Robbery = c(3.42, 
29.67, 16.9), Unlawful.acts.involving.controlled.drugs.or.precursors = c(70.26, 
494.05, 78.14), Country.Totals.per.000s = c(90, 620.75, 145.93
)), row.names = c("Albania", "Austria", "Bulgaria"), class = "data.frame")

由于您使用的是带有行名称的 data.frame,因此您可以使用

NoNACountry[!row.names(NoNACountry) %in% c("Spain", "Luxembourg"),]

很高兴将行名移到列中,这样它们就可以通过标准 data.frame 方法进行转换。

dplyr::rownames_to_column():

library(tidyverse)

mtcars %>% 
  rownames_to_column(var = "car_name") %>% 
  head()

           car_name  mpg cyl disp  hp drat    wt  qsec vs am gear carb
1         Mazda RX4 21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
2     Mazda RX4 Wag 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
3        Datsun 710 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
4    Hornet 4 Drive 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
5 Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
6           Valiant 18.1   6  225 105 2.76 3.460 20.22  1  0    3    1

在基础 R 中:

mtcars$car_name <- rownames(mtcars)

行名在列中后,您可以使用括号表示法过滤和 dplyr::filter()。例如:

# vector of car names to keep
cars_keep <- c("Volvo 142E", "Maserati Bora")

# base R
mtcars[which(mtcars$car_name %in% cars_keep), ]

# dplyr
filter(mtcars, car_name %in% cars_keep)