getN: #' Find the Nth Occurrence of a Value in a Vector

View source: R/alignTime.R

getNR Documentation

#' Find the Nth Occurrence of a Value in a Vector

Description

This function searches for the nth occurrence of a specified value ('w') in a vector ('x'). It can also find the nth occurrence where 'x' does not equal 'w' if 'notw' is TRUE. If the nth occurrence is not found, it returns a specified position beyond the last non-NA value.

Usage

getN(x, w, n, np1 = 1, notw = FALSE)

Arguments

x

Numeric vector in which to search for the value.

w

The value to search for in 'x'.

n

The occurrence number of the value to find.

np1

Offset to add to the final position if 'n' is not found. Default is 1, indicating the next position after the last non-NA value in 'x'.

notw

Logical; if TRUE, search for the nth occurrence where 'x' does not equal 'w'.

Value

Integer position of the nth occurrence of 'w' in 'x', adjusted by 'np1' if not found, or 1 if 'x' contains all NAs.

Examples

x <- c(1, 2, 3, 2, 4, 2, NA, NA)
getN(x, 2, 2) # Returns 4, the position of the second occurrence of 2
getN(x, 2, 3) # Returns 6, the position of the third occurrence of 2
getN(x, 5, 1) # Returns 9, one position after the last non-NA value, since 5 is not found
getN(x, 2, 1, np1 = 0, notw = TRUE) # Returns 1, the position of the first value not equal to 2

stueller/longCatEDA documentation built on March 9, 2024, 4:08 a.m.