Jordan Lee
Jordan Lee

Reputation: 1

Is there a function in R to combine names?

I have a list of 5 vectors. The list is called VECT. The 5 vectors are called VA, VB, VC, VD, VE. I have created a loop to add the vectors iteratively, getting VA+VA,VA+VB, VA+VC, VA+VD, VA+VE, VB+VA, VB+VB... I want to insert a line of code so that no only are the resulting vectors produced under the console (already done), they are also named. Like "VA+VA", "VA+VB" etc. How do I name like that? Thanks a lot!

Upvotes: 0

Views: 500

Answers (1)

r2evans
r2evans

Reputation: 161110

VECT <- c("VA", "VB", "VC")
setNames(nm = c(outer(VECT, VECT, paste, sep = "+")))
#   VA+VA   VB+VA   VC+VA   VA+VB   VB+VB   VC+VB   VA+VC   VB+VC   VC+VC 
# "VA+VA" "VB+VA" "VC+VA" "VA+VB" "VB+VB" "VC+VB" "VA+VC" "VB+VC" "VC+VC" 

Explanation:

  • outer does an "outer product": it runs the function (3rd argument) on each pair from the two vectors. In this case, it is effectively the same as

    for (nm1 in VECT) {
      for (nm2 in VECT) {
        paste(nm1, nm2, sep = "+")
      }
    }
    

    (and storing that in a vector)

  • c(...): outer returns a matrix (try it by itself!), so c(outer(...))` just unrolls it into a single vector.

  • setNames(nm = ...) takes a vector and names it based on its values. Typical use is setNames(object = vec, nm = vecnames) which is equivalent to names(vec) <- vecnames, but when object is missing, then it defaults to self-naming.

If order is critical here, one can always sort it:

sort(setNames(nm = c(outer(VECT, VECT, paste, sep = "+"))))
#   VA+VA   VA+VB   VA+VC   VB+VA   VB+VB   VB+VC   VC+VA   VC+VB   VC+VC 
# "VA+VA" "VA+VB" "VA+VC" "VB+VA" "VB+VB" "VB+VC" "VC+VA" "VC+VB" "VC+VC" 

Upvotes: 2

Related Questions