R中维度名称的数组联合

时间:2015-06-13 15:48:30

标签: arrays r vector set-union

我在R中有多个数组。每个数组都有以下结构:
一个。尺寸名称是字符 b。数组中的值是每个字符的频率。

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  

我希望将这些数组合并为一个,以保留每个字母的频率 期望的输出:

    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     

如何做到这一点?

1 个答案:

答案 0 :(得分:3)

尝试

 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

或者

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

数据

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"))