根据条件

时间:2016-05-20 01:04:32

标签: r

我们说我有以下data.frame,其中pos是位置坐标。我已经包含了一个变量阈值,其中val大于给定的阈值t。

set.seed(123)
n <- 20
t <- 0
DF <- data.frame(pos = seq(from = 0, by = 0.3, length.out = n),
                 val = sample(-2:5, size = n, replace = TRUE))
DF$thresh <- DF$val > t
DF

##    pos val thresh
## 1  0.0   0  FALSE
## 2  0.3   4   TRUE
## 3  0.6   1   TRUE
## 4  0.9   5   TRUE
## 5  1.2   5   TRUE
## 6  1.5  -2  FALSE
## 7  1.8   2   TRUE
## 8  2.1   5   TRUE
## 9  2.4   2   TRUE
## 10 2.7   1   TRUE
## 11 3.0   5   TRUE
## 12 3.3   1   TRUE
## 13 3.6   3   TRUE
## 14 3.9   2   TRUE
## 15 4.2  -2  FALSE
## 16 4.5   5   TRUE
## 17 4.8  -1  FALSE
## 18 5.1  -2  FALSE
## 19 5.4   0  FALSE
## 20 5.7   5   TRUE

如何获得val为正的区域坐标,即在上例中:

0.3 - 1.2,
1.8 - 3.9,
4.5 - 4.5,
5.7 - 5.7

我曾想过通过thresh拆分data.frame,然后从每个data.frame列表元素的第一行和最后一行访问pos,但这只会将所有TRUE和FALSE子集合在一起。有没有办法根据TRUE值将thresh变量转换为字符,并丢弃FALSE值?

split(DF, DF$thresh) # not what I want


## $`FALSE`
##    pos val thresh
## 1  0.0   0  FALSE
## 6  1.5  -2  FALSE
## 15 4.2  -2  FALSE
## 17 4.8  -1  FALSE
## 18 5.1  -2  FALSE
## 19 5.4   0  FALSE
## 
## $`TRUE`
##    pos val thresh
## 2  0.3   4   TRUE
## 3  0.6   1   TRUE
## 4  0.9   5   TRUE
## 5  1.2   5   TRUE
## 7  1.8   2   TRUE
## 8  2.1   5   TRUE
## 9  2.4   2   TRUE
## 10 2.7   1   TRUE
## 11 3.0   5   TRUE
## 12 3.3   1   TRUE
## 13 3.6   3   TRUE
## 14 3.9   2   TRUE
## 16 4.5   5   TRUE
## 20 5.7   5   TRUE

我尝试过的另一个笨重的事情是cumsum,但它又包含了错误的行:

split(DF, cumsum(DF$thresh == 0)) # not what I want but close to it...


## $`1`
##   pos val thresh
## 1 0.0   0  FALSE
## 2 0.3   4   TRUE
## 3 0.6   1   TRUE
## 4 0.9   5   TRUE
## 5 1.2   5   TRUE
## 
## $`2`
##    pos val thresh
## 6  1.5  -2  FALSE
## 7  1.8   2   TRUE
## 8  2.1   5   TRUE
## 9  2.4   2   TRUE
## 10 2.7   1   TRUE
## 11 3.0   5   TRUE
## 12 3.3   1   TRUE
## 13 3.6   3   TRUE
## 14 3.9   2   TRUE
## 
## $`3`
##    pos val thresh
## 15 4.2  -2  FALSE
## 16 4.5   5   TRUE
## 
## $`4`
##    pos val thresh
## 17 4.8  -1  FALSE
## 
## $`5`
##    pos val thresh
## 18 5.1  -2  FALSE
## 
## $`6`
##    pos val thresh
## 19 5.4   0  FALSE
## 20 5.7   5   TRUE

1 个答案:

答案 0 :(得分:7)

以下是data.table的一个选项。我们使用rleid创建分组变量,基于'thresh'和split对'pos'进行子集化。

DT <- setDT(DF)[,pos[thresh] ,.(gr=rleid(thresh))]
split(DT$V1, DT$gr)
#$`2`
#[1] 0.3 0.6 0.9 1.2

#$`4`
#[1] 1.8 2.1 2.4 2.7 3.0 3.3 3.6 3.9

#$`6`
#[1] 4.5

#$`8`
#[1] 5.7

或者,我们可以使用rle中的base R来创建分组变量,然后使用split来创建分组变量

gr <- inverse.rle(within.list(rle(DF$thresh), values <- seq_along(values)))
with(DF, split(pos[thresh], gr[thresh]))

或者@thelatemail提到,cumsum也可以在使用'thresh'进行子集化后用于分组。

 with(DF, split(pos[thresh],cumsum(!thresh)[thresh]))