3

我有两个矩阵,我想以交替的方式交织/交错/堆叠在彼此之上/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)(如果我有两个字符串,这似乎可以解决问题)没有效果

4

1 回答 1

1

这里有两种选择。

首先,假设我们必须以“x”和“y”开头,您可以interleave从“gdata”包中尝试:

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

其次,假设我们可以从“ranks”、“names”和“universities”开始,您可以使用 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(来自“reshape2”或“data.table”)。这将允许您添加另一个变量来指示值代表的测量类型。

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
于 2015-12-29T02:40:44.177 回答