我有一個經濟資料的資料框,其中包括嬰兒死亡率和世界地區。我提取了每個區域的例外值。
income infant region oil
Saudi.Arabia 1530 650.0 Asia yes
Afganistan 75 400.0 Asia no
Libya 3010 300.0 Africa yes
Zambia 310 259.0 Africa no
Guinea 79 216.0 Africa no
Burma 73 200.0 Asia no
我有(1)例外值的值和(2)每個值對應區域的名稱。
> out$out # values
[1] 300.0 170.0 650.0 400.0 44.8 43.3
> out$names[out$group] # name of region corresponding to each outlier
[1] "Africa" "Americas" "Asia" "Asia" "Europe" "Europe"
我現在想過濾與每個值對對應的行的資料框。例如,我想要infant值為 170 且region為 Americas的行的 rowname 。我不能使用兩個串列中列值的聯合條件,因為還有其他行具有相同的值但不同的組(因為它們不是組中的例外值)。
我知道我可以分兩步完成,但我想知道 R 中是否有更優雅的解決方案來做到這一點。
非常感謝!
uj5u.com熱心網友回復:
df <- data.frame(income = c(1530, 75, 3010, 310, 79, 73),
infant = c(650, 400, 300, 259, 216, 200),
region = c("Asia", "Asia", "Africa", "Africa", "Africa", "Asia"),
oil = c("yes", "no", "yes", "no", "no", "no"),
row.names = c("Saudi.Arabia", "Afganistan", "Libya",
"Zambia", "Guinea", "Burma"))
df
# income infant region oil
# Saudi.Arabia 1530 650 Asia yes
# Afganistan 75 400 Asia no
# Libya 3010 300 Africa yes
# Zambia 310 259 Africa no
# Guinea 79 216 Africa no
# Burma 73 200 Asia no
x <- c(300.0, 170.0, 650.0, 400.0, 44.8, 43.3)
y <- c("Africa", "Americas", "Asia", "Asia", "Europe", "Europe")
df[paste0(df$infant, df$region) %in% paste0(x, y),]
# income infant region oil
# Saudi.Arabia 1530 650 Asia yes
# Afganistan 75 400 Asia no
# Libya 3010 300 Africa yes
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/341302.html
上一篇:如何在我的所有資料上處理R腳本
