有没有更优雅的方法来解决这个问题?
对于每个TRUE值,我都在寻找最接近的前和后FALSE值的位置。
数据:
vec <- c(FALSE, TRUE, TRUE, FALSE, TRUE, FALSE)
期望的结果:(类似)
pos start end
[1,] 2 1 4
[2,] 3 1 4
[3,] 5 4 6
结果的第一行的说明:
已经有效的解决方案:
pos = which(vec)
f_pos = which(!vec)
t(
sapply(pos, function(x){ s <- rev(f_pos[f_pos < x])[1]; e <- f_pos[x < f_pos][1]; return(data.frame(pos = x, start = s, end = e)) })
)
答案 0 :(得分:3)
您可以像@import bourbon/bourbon
header
+display(flex)
+flex-flow(row-reverse wrap)
+justify-content(flex-start)
+align-items(center)
+align-content(flex-start)
width: 100%
定义的间隔一样操作,并使用FALSE
查找正确的间隔:
data.table::foverlaps
您可以进一步对列进行重新排序,并仅保留所需的列:
library(data.table)
# put your objects in data.tables:
f_pos_inter <- data.table(start=head(f_pos, -1), end=tail(f_pos, -1))
pos_inter <- data.table(start=pos, end=pos)
# define the keys:
setkeyv(pos_inter, c("start", "end")); setkeyv(f_pos_inter, c("start", "end"))
res <- foverlaps(pos_inter, f_pos_inter)
# start end i.start i.end
#1: 1 4 2 2
#2: 1 4 3 3
#3: 4 6 5 5
NB:如果res[, i.end:=NULL]
setcolorder(res, c(3, 1, 2))
setnames(res, "i.start", "pos")
res
# pos start end
#1: 2 1 4
#2: 3 1 4
#3: 5 4 6
以start
结尾,这将在end
和vec
两列中给出NA
答案 1 :(得分:3)
使用Public Sub ShowHide(PanelName As String)
Me.Controls.OfType(Of Panel).ToList().ForEach(Sub(p) p.Visible = (p.Name = PanelName))
End Sub
findInterval
如果我们稍微拉伸您的“类似”,则简单的pos <- which(vec)
b <- which(!vec)
ix <- findInterval(pos, b)
cbind(pos, from = b[ix], to = b[ix + 1])
# pos from to
# [1,] 2 1 4
# [2,] 3 1 4
# [3,] 5 4 6
可以做到:
cut
如果向量以data.frame(pos, rng = cut(pos, b))
# pos rng
# 1 2 (1,4]
# 2 3 (1,4]
# 3 5 (4,6]
结尾,则TRUE
解决方案将在“至”列中给出findInterval
。在NA
中,最后一个“时间间隔”被编码为cut
。