交替,交织或交织两个矩阵

时间:2015-12-29 00:41:07

标签: r matrix alternating

我有两个矩阵,我想以交替的方式交替交织/交错/堆叠在彼此/ rbind之上。

ranks=1:3
names=c("Karl", "Klaus", "Mary")
x <- cbind(ranks, names)

universities=c("Cape Town", "London", "Berlin")
y <- cbind(rep("", 3), universities)

x的一行之后,我需要一行y

     [,1] [,2]       
[1,] "1"  "Karl"     
[2,] ""   "Cape Town"
[3,] "2"  "Klaus"      
[4,] ""   "London"   
[5,] "3"  "Mary"   
[6,] ""   "Berlin" 

我试过matrix(rbind(x, y), ncol=2)(如果我有两个字符串似乎可以解决问题)没有效果

1 个答案:

答案 0 :(得分:1)

以下是两种选择。

首先,假设我们必须从&#34; x&#34;开始和&#34; y&#34;,您可以尝试{&#34; gdata&#34;}中的interleave包:

library(gdata)
interleave(x, y)
#      ranks names      
# [1,] "1"   "Karl"     
# [2,] ""    "Cape Town"
# [3,] "2"   "Klaus"    
# [4,] ""    "London"   
# [5,] "3"   "Mary"     
# [6,] ""    "Berlin"

其次,假设我们可以从&#34; rank&#34;,&#34; names&#34;,&#34; university&#34;开始,你可以使用base R,如下所示:

cbind(c(t(cbind(ranks, ""))), c(t(cbind(names, universities))))
#      [,1] [,2]       
# [1,] "1"  "Karl"     
# [2,] ""   "Cape Town"
# [3,] "2"  "Klaus"    
# [4,] ""   "London"   
# [5,] "3"  "Mary"     
# [6,] ""   "Berlin"

然而,更好的选择是使用类似melt的内容(来自&#34; reshape2&#34;或&#34; data.table&#34;)。这将允许您添加另一个变量,该变量指示值表示的测量类型。

library(data.table)
melt(data.table(ranks, names, universities), "ranks")
#    ranks     variable     value
# 1:     1        names      Karl
# 2:     2        names     Klaus
# 3:     3        names      Mary
# 4:     1 universities Cape Town
# 5:     2 universities    London
# 6:     3 universities    Berlin

或者,为了符合您的预期顺序:

library(data.table)
setorder(melt(data.table(ranks, names, universities), "ranks"), ranks)[]
#    ranks     variable     value
# 1:     1        names      Karl
# 2:     1 universities Cape Town
# 3:     2        names     Klaus
# 4:     2 universities    London
# 5:     3        names      Mary
# 6:     3 universities    Berlin