Combination of named vectors

I named the vectors that I would like to combine as follows:

v1 <- c(0,1,2,3)
v2 <- c(0,1,2,3)
v3 <- c(0,1,2,3)
names(v1) <- c("This","is","an","example")
names(v2) <- c("This","great","value","random")
names(v3) <- c("This","This","and","This")

      

expected output for v1 and v2:

This is an example great value random
0    1  2  3       1     2     3

      

and for v1 and v3:

This is an example This and This
0    1  2  3       1    2   3

      

As you can see, vectors are simply related to each other if the names are different. If the resulting vector contains multiple occurrences of the name, it is stored once if the corresponding value is the same, but multiple times if the values ​​differ from each occurrence. I do not know if I am clear what I would like to achieve.

Is there a way to achieve something like this? Thanks you

+3


source to share


1 answer


I would make a helper function like:

Combiner <- function(vec1, vec2, vecOut = TRUE) {
  temp <- unique(rbind(data.frame(as.table(vec1)),
                       data.frame(as.table(vec2))))
  if (isTRUE(vecOut)) setNames(temp$Freq, temp$Var1)
  else temp
}

      

The bottom line is comparing both names and values, and it was easier for me to just paste that into the form data.frame

.

The usage would then be:

Combiner(v1, v2)
#    This      is      an example   great   value  random 
#       0       1       2       3       1       2       3 
Combiner(v1, v3)
#    This      is      an example    This     and    This 
#       0       1       2       3       1       2       3 

      




For any number of vectors, you can change the function to be something like:

Combiner <- function(..., vecOut = TRUE) {
  dots <- list(...)
  if (any(is.null(sapply(dots, names)))) stop("All vectors must be named")
  temp <- unique(do.call(rbind, lapply(dots, function(x) {
    data.frame(Name = names(x), Value = unname(x), stringsAsFactors = FALSE)
  })))
  if (isTRUE(vecOut)) setNames(temp$Value, temp$Name)
  else temp
}

      

While the first version will only work with numeric named vectors (as it does as.table

), the second version should also work with named character vectors.

+4


source







All Articles