我有一个包含位置 ( 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
该位置的所有区域是否> 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 package 创建于 2018-07-25 (v0.2.0.9000)。
关于R:基于一列按两个条件对数据框进行子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51516475/