我有一个包含位置(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
在该位置s为> 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 。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句