gpt4 book ai didi

r - 对齐R中字符矩阵中的行

转载 作者:行者123 更新时间:2023-12-04 14:48:20 26 4
gpt4 key购买 nike

我有一个结构如下的字符矩阵:

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)

关于如何实现这种重组的想法?它可以通过循环和会计来完成,但肯定有一种我缺少的更优雅的方式。

最佳答案

library(reshape2)

ncols = ncol(TheMatrix)
nrows = nrow(TheMatrix)

dcast(as.data.frame(na.omit(cbind(c(TheMatrix[,seq(1,ncols,2)]),
c(TheMatrix[,seq(2,ncols,2)]),
rep(colnames(TheMatrix)[seq(2,ncols,2)],
each = nrows)))),
V1 ~ V3, value.var = 'V2')
# V1 B1 B2 B3
#1 bird 10 <NA> <NA>
#2 cow 7 9 <NA>
#3 deer <NA> 7 27
#4 dog 1 <NA> <NA>
#5 gnu 5 <NA> 2
#6 mouse 8 <NA> 7
#7 rat <NA> 50 <NA>
#8 sheep 21 <NA> <NA>
#9 skunk 2 <NA> <NA>
#10 snake <NA> 3 <NA>
#11 tiger 3 1 <NA>

这里发生了很多事情(每一个都非常简单),要理解,只需自行运行每一点(从内部开始并走出去)。

关于r - 对齐R中字符矩阵中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19191443/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com