HenrikBengtsson / R.utils

🔧 R package: R.utils (this is *not* the utils package that comes with R itself)
https://henrikbengtsson.github.io/R.utils/
62 stars 14 forks source link

R.utils::insert unable to add adjacent insertions...? #127

Closed brooksambrose closed 3 years ago

brooksambrose commented 3 years ago

I am unable to insert two adjacent items into a series using R.utils::insert. Please let me know if this is actually possible using the command as is without post processing, otherwise I would submit that it is a reasonable thing to expect the function to do.

# should in principle be able to produce this pattern
c('A','B','a','b','c','d','C','e','f')
#> [1] "A" "B" "a" "b" "c" "d" "C" "e" "f"

# error
R.utils::insert(x=head(letters),at=c(1,1,4),values=LETTERS[1:3])
#> [2021-01-23 20:24:39] Exception: Argument 'ats' contains duplicated indices: 1,
#> 1, 4

# not desired result
R.utils::insert(x=head(letters),at=c(1,2,4),values=LETTERS[1:3])
#> [1] "A" "a" "B" "b" "c" "C" "d" "e" "f"

Created on 2021-01-23 by the reprex package (v0.3.0)

HenrikBengtsson commented 3 years ago

Hi. The following works:

> R.utils::insert(x=head(letters), ats=c(1, 4), values=list(LETTERS[1:2], LETTERS[3]))
[1] "A" "B" "a" "b" "c" "C" "d" "e" "f"

R.utils::insert(x=head(letters), at=c(1,1,4), values=LETTERS[1:3])

into the above automatically using something like:

ats <- c(1,1,4)
values <- LETTERS[1:3]
valuesL <- by(values, INDICES = ats, FUN = identity)
attributes(valuesL) <- NULL
R.utils::insert(x=head(letters), ats=unique(ats), values=valuesL)

While doing this, I also noticed that insert() is a little bit picky about:

HenrikBengtsson commented 3 years ago

I've added support for what you've tried/expected to the develop branch (=next release), i.e.

> R.utils::insert(x=head(letters), ats=c(1,1,4), values=LETTERS[1:3])
[1] "A" "B" "a" "b" "c" "C" "d" "e" "f"