r - Combination of named vectors -


i have named vectors i'd combine 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 result v1 , v2:

this example great value random 0    1  2  3       1     2     3 

and v1 , v3:

this example , 0    1  2  3       1    2   3 

as can see, vectors bound if names differ. if there several occurances of name in resulting vector, kept once if corresponding value same, multiple times if values differ each occurence. don't know if made clear i'd achieve.

is way achieve this? thank you

i make helper function, this:

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 point compare both names , values, , found easiest put form of data.frame.

usage be:

combiner(v1, v2) #              example   great   value  random  #       0       1       2       3       1       2       3  combiner(v1, v3) #              example        ,     #       0       1       2       3       1       2       3  

for number of vectors, can modify function like:

combiner <- function(..., vecout = true) {   dots <- list(...)   if (any(is.null(sapply(dots, names)))) stop("all vectors must 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 first version work numeric named vectors (since makes use of as.table), second version should work named character vectors.


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -