这里有两种选择。
首先,假设我们必须以“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