[英]How to find several values conditionally from a vector?
我有几个系列递增数字的向量。 例如,我在向量 v 中有 3 个系列:
v <- c(1,2,3,4,5,
2,2.5,2.9,3.4,7,
1,2,7,7.5,8,9)
我想找到这些系列中大于或等于 3 的第一个数字的位置。 另外,我也想找各系列第一号的position。
预期结果:
# for greater than equal 3
First position: 3 (3)
Second position: 9 (3.4)
Third position 13 (7)
# for the first position
1, 6, 11
创建一个变量来表示每个系列:
inds <- cumsum(c(TRUE, diff(v) < 0))
在每个系列中找到大于等于 3 的第一个数字的 position:
as.numeric(tapply(seq_along(v), inds, function(x) x[v[x] >= 3][1]))
#[1] 3 9 13
查找系列中第一个数字的 position
match(unique(inds), inds)
#[1] 1 6 11
使用 Position 的基础 R:
v_l <- lengths(split(v, cumsum(c(TRUE, diff(v) < 0))))
idx <- cumsum(c(0, v_l[-1])) + sapply(split(v, cumsum(c(TRUE, diff(v) < 0))),
function(x){Position(function(y) y >= 3, x)})
cat(paste0(sapply(seq_along(idx), function(i){
paste0(i, ifelse(i == 1, "st",
ifelse(i == 2, "nd",
ifelse(i == 3, "rd", "th"))),
" Position: ", idx[i], "(", v[idx[i]], ")")
}
), collapse = "\n"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.