Skip to contents

It is often helpful to insert an item into a list after another known item rather than at an index of the list as base::append() does. This function provides that functionality.

Usage

insert_after(
  x,
  after = NULL,
  values,
  .after_all = TRUE,
  .equals_function = `==`
)

Arguments

x

a list into which values is to be inserted

after

the object in x after which after will be inserted

values

the object to be inserted into x

.after_all

a boolean telling whether to insert values after after all instances of after (when TRUE, the default) or only the first instance of after (when FALSE).

.equals_function

insertion of values occurs at which(.equals_function(x, after)). Default is ==.

Value

a modified version of x

Details

If there are multiple copies of after in x, values is inserted after each after, unless .after_all = FALSE.

The positions at which insertions will occur are determined by the == operator. I.e., values are inserted in x after each position in x where x == after is true.

Note that length(after) must be 1.

If is.null(after), values is inserted once at the end of the list.

Examples

insert_after(list("a", "b", "c", "d", "c"), after = "c", values = "1")
#> [[1]]
#> [1] "a"
#> 
#> [[2]]
#> [1] "b"
#> 
#> [[3]]
#> [1] "c"
#> 
#> [[4]]
#> [1] "1"
#> 
#> [[5]]
#> [1] "d"
#> 
#> [[6]]
#> [1] "c"
#> 
#> [[7]]
#> [1] "1"
#>