Search code examples
rstringfunctionvectorcharacter

Add signs (- or +) back to a string vector in R


I have a string Vector as well as a set of index values. The index values can be sometimes negative or positive.

But we can use Vector2 <- Vector[abs(index)] to extract our desired elements from our initial Vector.

Question: Is it possible to add back the signs (- or +) from index between the elements of Vector2 to achieve the Desired_output below?

(NOTE: This is a toy example. Vector can be of any size or contain any shape of character elements and index can be of any length of course smaller than Vector. A functional answer is appreciated.)

Vector <- c("advanced baseline", "beginner baseline", "intermediate baseline", 
  "advanced post1", "beginner post1", "intermediate post1", "advanced post2", 
  "beginner post2", "intermediate post2")

index = c(8,-2,-7,1)

( Vector2 <- Vector[abs(index)] )

Desired_output <- "beginner post2 - beginner baseline - advanced post2 + advanced baseline"

Solution

  • You can use paste to merge the signs with vector elements. I guess you want to retain a minus sign for the first element but not a plus so that is removed with sub.

    add_signs <- function(vec, ind) {
      merged <- paste(ifelse(ind < 0, '-', '+'), 
                      vec[abs(ind)], 
                      collapse=' ')
      sub('^\\+ ', '', merged)
    }
    
    add_signs(Vector, index)
    # [1] "beginner post2 - beginner baseline - advanced post2 + advanced baseline"