Union of arrays over dimension names in R -
i have multiple arrays in r. each array has following structure:
a. dimension names characters.
b.the values in array frequency of each character.
c k j d l n s 5 5 3 1 1 1 1 1 d j o h k q z r 4 4 4 3 2 2 2 1 1 1
i want combine these arrays 1 such frequency of each letter retained.
desired output:
c k j d l n s o h 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 done?
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 d l n s o h 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 d l n s o h 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"))
Comments
Post a Comment