[英]R: subset dataframe by two conditions based on one column
我有一個包含位置( loc
)的數據框,其中每個位置都有兩個區域( type
)和每個區域中的干擾區域( area
)。 從我的數據框中,我想保留兩個區域都受干擾的位置。
我以為我可以通過按兩個條件設置數據子集來簡單地做到這一點,但是使用AND條件(&)
subset(dd, (dd$type == "npr" & dd$area > 0 ) & (dd$type == "buff" & dd$area > 0 ) )
給我空輸出
[1] loc type area
<0 rows> (or 0-length row.names)
並使用“ OR”條件(|)
subset(dd, (dd$type == "npr" & dd$area > 0 ) | (dd$type == "buff" & dd$area > 0 ) )
不是我想要的
loc type area
1 a npr 10
2 a buff 20
4 b buff 10
5 c npr 5
7 d npr 5
8 d buff 5
在兩種區域類型中,如何正確子集擾動區域> 0的位置?
我的虛擬數據:
loc<-c("a", "a", "b", "b", "c", "c", "d", "d")
type= rep(c("npr", "buff"), 4)
area = c(10,20,0,10,5,0,5,5)
dd<-data.frame(loc, type, area)
所需的輸出:
loc type area
1 a npr 10
2 a buff 20
3 d npr 5
4 d buff 5
您需要計算一個分組摘要以實現此目的。 也就是說,你要找出每個loc
如果所有的area
在那只位置是> 0。我一直覺得基礎R有點尷尬的分組統計數據,但在這里是實現的一個方法。
首先,使用tapply()
以確定每個loc
它是否應當被包括或不:
(include <- tapply(dd$area, dd$loc, function(x) all(x > 0)))
#> a b c d
#> TRUE FALSE FALSE TRUE
然后,我們可以使用loc
值對結果進行索引,以得到一個適合於dd
子集的向量,其中:
include[dd$loc]
#> a a b b c c d d
#> TRUE TRUE FALSE FALSE FALSE FALSE TRUE TRUE
dd[include[dd$loc], ]
#> loc type area
#> 1 a npr 10
#> 2 a buff 20
#> 7 d npr 5
#> 8 d buff 5
我們還可以將這些步驟放到一個subset()
調用中,以避免創建額外的變量:
subset(dd, tapply(area, loc, function(x) all(x > 0))[loc])
#> loc type area
#> 1 a npr 10
#> 2 a buff 20
#> 7 d npr 5
#> 8 d buff 5
另外,您可以使用dplyr :
library(dplyr)
dd %>%
group_by(loc) %>%
filter(all(area > 0))
#> # A tibble: 4 x 3
#> # Groups: loc [2]
#> loc type area
#> <fct> <fct> <dbl>
#> 1 a npr 10
#> 2 a buff 20
#> 3 d npr 5
#> 4 d buff 5
由reprex軟件包 (v0.2.0.9000)創建於2018-07-25。
我將首先重塑:
loc<-c("a", "a", "b", "b", "c", "c", "d", "d")
type= rep(c("npr", "buff"), 4)
area = c(10,20,0,10,5,0,5,5)
dd<-data.frame(loc, type, area)
library(reshape2)
dd_wide <- dcast(dd, loc ~ type, value.var = "area")
mask <- subset(dd_wide, buff > 0 & npr > 0)[["loc"]]
subset(dd, loc %in% mask)
# one line:
subset(dd, loc %in% subset(dcast(dd, loc ~ type, value.var = "area"), buff > 0 & npr > 0)[["loc"]])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.