I have a vector of several series of increasing numbers. For example, I have 3 series here in a vector v:
v <- c(1,2,3,4,5,
2,2.5,2.9,3.4,7,
1,2,7,7.5,8,9)
I would like to find the positions of the first numbers that greater than or equal to 3 in those series. In addition, I would also like to find the position of the first number in each series.
Expected result:
# 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
Create a variable to denote each series:
inds <- cumsum(c(TRUE, diff(v) < 0))
Find the position of first number greater the equal to 3 in each series:
as.numeric(tapply(seq_along(v), inds, function(x) x[v[x] >= 3][1]))
#[1] 3 9 13
Find position of first number in series
match(unique(inds), inds)
#[1] 1 6 11
Base R using Position:
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"))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.