Search code examples
rstringfunctionvector

Reorder a vector element to be second in R


Suppose we have some two-element string vectors like A, B, C, ... below. We only know one of the elements which is saved as object second.

Is there a way to make the second to be always the second element in A, B, C, ...?

A = c("time","prof") # --> must become `c("prof", "time")`

B = c("prof", "time") # --> remains Unchanged

C = c("time","ziba") # --> must become `c("ziba", "time")`

second = "time"

Solution

  • You can create a helper function to move a particular value to the end of a vector

    move_last <- function(x, v) {
      c(setdiff(x, v), intersect(x,v))
    }
    

    This works with the given vectors

    move_last(A, second)
    # [1] "prof" "time"
    move_last(B, second)
    # [1] "prof" "time"
    move_last(C, second)
    # [1] "ziba" "time"
    move_last(c("apple", "banana"), second)
    # [1] "apple"  "banana"