作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
假设我有以下 data.frame,其中 pos 是位置坐标。我已经包含了一个变量 thresh,其中 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
0.3 - 1.2,
1.8 - 3.9,
4.5 - 4.5,
5.7 - 5.7
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
最佳答案
这是 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]))
cumsum
也可用于在使用 'thresh' 进行子集化后进行分组。
with(DF, split(pos[thresh],cumsum(!thresh)[thresh]))
关于r - 根据条件拆分数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37336361/
我是一名优秀的程序员,十分优秀!