根据条件拆分数据框

5
假设我有以下数据框,其中pos是位置坐标。我还包括一个变量thresh,在此变量中,val大于给定的阈值t。

请注意,这里的“数据框”指的是在R编程语言中使用的一种数据结构。
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

如何获取值为正的区域坐标,即在上面的示例中:

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

我想通过thresh将数据框分割,然后访问每个数据框列表元素的第一行和最后一行中的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

对于split命令,我没有看到任何问题。不过,为什么不直接使用DF[DF$thresh==T, ],而不是使用split呢? - Adam Quek
@AdamQuek 因为那样会将所有TRUE行组合在一起,但我想要访问确切的“区域”。按照你的方式会给我0.3-5.7的限制... - PeterQ
1个回答

8

以下是使用 data.table 的一种选项。我们使用 rleid 创建分组变量,根据 'thresh' 对 'pos' 进行子集,并使用 split 进行分割。

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

或者我们可以使用base R中的rle创建分组变量,然后根据该变量进行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]))

4
替代方案 - split(DF$pos[DF$thresh], cumsum(!DF$thresh)[DF$thresh]) (该代码行为R语言中的代码) - thelatemail

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接