【问题标题】:Removing outliers linear regression [duplicate]去除异常值线性回归[重复]
【发布时间】:2021-12-07 17:27:33
【问题描述】:

我正在通过线性回归运行数据并发现异常值。我试过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... 是列。我已经能够通过here的指导在其他代码中使用drop = FALSE,但我无法在此处合并这种方法

数据框信息如下

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")

【问题讨论】:

  • 是的!太棒了-非常感谢。我投票给你

标签: r dataframe graph linear-regression outliers


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    最好将行名移动到列中,这样它们就可以通过标准的 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)
    

    【讨论】:

      猜你喜欢
      • 2018-12-18
      • 2018-10-04
      • 2016-07-01
      • 1970-01-01
      • 2015-07-09
      • 2015-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多