Union of arrays over dimension names in R

94 views Asked by At

I have multiple arrays in R. Each array has following structure:
a. The dimension names are characters.
b.The values in array are frequency of each character.

c k j a d l n s      
5 5 3 1 1 1 1 1      

d j o a h i k q z r
4 4 4 3 2 2 2 1 1 1  

I want to combine these arrays into one such that frequency of each letter is retained.
Desired output:

    c k j a d l n s o h i k q z r      
[1] 5 5 3 1 1 1 1 1 0 0 0 0 0 0 0     
[2] 0 0 4 3 4 0 0 0 4 2 2 2 1 1 1     

How can this be done?

1

There are 1 answers

0
akrun On

Try

 Un1 <- union(names(v1), names(v2))
 res <- do.call(rbind,lapply(list(v1, v2), function(x) 
           setNames(x[match(Un1, names(x))], Un1)))
 res[is.na(res)] <- 0
 res
 #     c k j a d l n s o h i q z r
 #[1,] 5 5 3 1 1 1 1 1 0 0 0 0 0 0
 #[2,] 0 2 4 3 4 0 0 0 4 2 2 1 1 1

Or

res1 <- as.matrix(merge(as.data.frame.list(v2), as.data.frame.list(v1),
            all=TRUE)[Un1])
res1[is.na(res1)] <- 0
res1
#     c k j a d l n s o h i q z r
#[1,] 5 5 3 1 1 1 1 1 0 0 0 0 0 0
#[2,] 0 2 4 3 4 0 0 0 4 2 2 1 1 1

data

v1 <- structure(c(5, 5, 3, 1, 1, 1, 1, 1), .Names = c("c", "k", "j", 
   "a", "d", "l", "n", "s"))

v2 <- structure(c(4, 4, 4, 3, 2, 2, 2, 1, 1, 1), .Names = c("d", "j",
   "o", "a", "h", "i", "k", "q", "z", "r"))