我正在通過線性回歸運行資料并發現例外值。我試過了,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)
我想我不知何故丟失了行名稱,因為我認為Robbery和Unlawful.acts...已經成為向量?我使用的國家名稱是行標簽,而Robbery和Unlawful.acts...是列。我已經能夠通過這里的指導,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")
uj5u.com熱心網友回復:
由于您使用的是帶有行名稱的 data.frame,您可以使用
NoNACountry[!row.names(NoNACountry) %in% c("Spain", "Luxembourg"),]
uj5u.com熱心網友回復:
將行名移動到列是很好的,這樣它們就可以通過標準的 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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/328188.html
下一篇:計算組id中列的某些值
