我使用线性回归建模我的数据。我想多次运行Bonferroni离群值测试并从我的数据中删除相应的记录。我的问题是:我无法从outlierResult中提取id。这是可重现的代码。我想根据伪代码编写一个while循环。我在R中编码。
# URL <- "http://www.math.uah.edu/stat/data/Galton.csv"
# download.file(URL, destfile = "./galton.csv", method="curl")
galton <-read.csv("galton.csv")
attach(galton)
dim(galton)
head(galton)
##creating outliers
set.seed(1)
random_index <- sample(1:nrow(galton), size = 5, replace = FALSE, prob = NULL)
print(random_index)
galton[random_index,"Height"] = galton[random_index,"Height"] +100
set.seed(2)
random_index2 <- sample(1:nrow(galton), size = 5, replace = FALSE, prob = NULL)
galton[random_index2,"Height"] = galton[random_index2,"Height"] +75
set.seed(3)
random_index3 <- sample(1:nrow(galton), size = 5, replace = FALSE, prob = NULL)
galton[random_index3,"Height"] = galton[random_index3,"Height"] +50
linear_reg <- lm(Height~Father+Mother,data=galton)
require(car, quietly=TRUE)
outlierResult <-outlierTest(linear_reg)
outlierResult
# the pseudocode
# while outlierResult is not empty
# remove the corresponding records
# linear_reg <- lm(Height~Father+Mother,data=galton)
# outlierResult <-outlierTest(linear_reg)
答案 0 :(得分:0)
请参阅下文。诀窍是要注意,如果我正确读取它,异常结果会给出行名称。
library(car, quietly=TRUE)
galton <-read.csv("http://www.math.uah.edu/stat/data/Galton.csv")
attach(galton)
dim(galton)
head(galton)
##creating outliers
set.seed(1)
random_index <- sample(1:nrow(galton), size = 5, replace = FALSE, prob = NULL)
print(random_index)
galton[random_index,"Height"] = galton[random_index,"Height"] +100
set.seed(2)
random_index2 <- sample(1:nrow(galton), size = 5, replace = FALSE, prob = NULL)
galton[random_index2,"Height"] = galton[random_index2,"Height"] +75
set.seed(3)
random_index3 <- sample(1:nrow(galton), size = 5, replace = FALSE, prob = NULL)
galton[random_index3,"Height"] = galton[random_index3,"Height"] +50
currentData <- galton
linear_reg <- lm(Height~Father+Mother,data=currentData)
outlierResult <-outlierTest(linear_reg)
outlierResult
while(length(outlierResult)!=0){
exclusionRows <-names(outlierResult[[1]])
inclusionRows <- !(rownames(currentData) %in% exclusionRows)
currentData <- currentData[inclusionRows,]
linear_reg <- lm(Height~Father+Mother,data=currentData)
outlierResult <-outlierTest(linear_reg)
}