gpt4 book ai didi

r - 交替、交织或交织两个矩阵

转载 作者:行者123 更新时间:2023-12-02 03:19:22 27 4
gpt4 key购买 nike

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

最佳答案

这里有两种选择。

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

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

关于r - 交替、交织或交织两个矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34502866/

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