Learn R Programming

str2str (version 1.0.0)

inbtw: Elements Inbetween Values Within a (Atomic) Vector

Description

inbtw extracts all elements inbetween (by position) two specific elements of a (atomic) vector. This can be useful when working with rownames and colnames since seq does not work with names. Primary for character vectors but can be used with other typeof.

Usage

inbtw(x, from, to, left = TRUE, right = TRUE)

Value

vector of the same type as x that only includes elements in x

inbetween (by position) from and to, which may or may not include from and to themselves, depending on left and right, respectively.

Arguments

x

atomic vector.

from

vector of length 1 specifying the element to start with on the left.

to

vector of length 1 specifying the element to end with on the right.

left

logical vector of length 1 specifying whether the leftmost element, from, should be included in the return object.

right

logical vector of length 1 specifying whether the rightmost element, to, should be included in the return object.

Details

An error is returned if either from or to don't appear in x or appear more than once in x.

Examples

Run this code
# character vector
row_names <- inbtw(x = row.names(LifeCycleSavings), from = "China", to = "Peru")
LifeCycleSavings[row_names, ] # default use
row_names <- inbtw(x = row.names(LifeCycleSavings), from = "China", to = "Peru",
   right = FALSE, left = FALSE)
LifeCycleSavings[row_names, ] # use with right and left arguments FALSE
try_expr(inbtw(x = row.names(LifeCycleSavings), from = "china",
   to = "peru")) # error due to `from` and `to` not appearing in `x`
try_expr(inbtw(x = rep.int(x = row.names(LifeCycleSavings), times = 2), from = "China",
   to = "Peru")) # error due to `from` and `to` appearing more than once in `x`
# numeric vector
vec <- sample(x = 150:199, size = 50)
inbtw(x = vec, from = 150, to = 199)
# list vector (error)
lst <- list(FALSE, 3L, 9.87, "abc", factor("lvl"))
try_expr(inbtw(x = lst, from = 3L, to = "abc")) # error because `lst` is a
   # list vector and not an atomic vector

Run the code above in your browser using DataLab