我有一个结构如下的字符矩阵:
dog 1 cow 9 mouse 7
bird 10 tiger 1 gnu 2
tiger 3 deer 7 deer 27
skunk 2 rat 50 NA NA
mouse 8 snake 3 NA NA
cow 7 NA NA NA NA
sheep 21 NA NA NA NA
gnu 5 NA NA NA NA
想象这是一个语言环境中的动物矩阵,每个语言环境的数据由连续的列对定义。有些动物可能在不同地区之间很常见,但地区也可能有独特的动物。最终我想制作这个数据的热图,因此需要重新排序这个矩阵以具有一个结构,其中所有类型的动物都有一个列,每个区域设置对应于数字的连续列:
dog 1 NA NA
tiger 3 1 NA
skunk 2 NA NA
mouse 8 NA NA
cow 7 9 NA
sheep 21 NA NA
gnu 5 NA 2
deer NA 7 27
rat NA 50 NA
snake NA 3 NA
mouse NA NA 7
bird 10 NA NA
换句话说,我有
A1 <- c("dog", "bird", "tiger", "skunk", "mouse", "cow", "sheep", "gnu")
B1 <- as.character(c(1, 10, 3, 2, 8, 7, 21, 5))
A2 <- c("cow", "tiger", "deer", "rat", "snake", NA, NA, NA)
B2 <- as.character(c(9, 1, 7, 50, 3, NA, NA, NA))
A3 <- c("mouse", "gnu", "deer", NA, NA, NA, NA, NA)
B3 <- as.character(c(7, 2, 27, NA, NA, NA, NA, NA))
TheMatrix <- cbind(A1, B1, A2, B2, A3, B3)
并且想要
a1 <- c("dog", "tiger", "skunk", "mouse", "cow", "sheep", "gnu", "deer", "rat", "snake", "mouse", "bird")
b1 <- as.character(c(1, 3, 2, 8, 7, 21, 5, NA, NA, NA, NA, 10))
b2 <- as.character(c(NA, 1, NA, NA, 9, NA, NA, 7, 50, 3, NA, NA))
b3 <- as.character(c(NA, NA, NA, NA, NA, NA, 2, 27, NA, NA, 7, NA))
DesiredResult <- cbind(a1, b1, b2, b3)
关于如何实现这种重组的想法?它可以通过循环和会计来完成,但肯定有一种更优雅的方式,我错过了。