gpt4 book ai didi

将R中矩阵中的二维数组的行 reshape 为列

转载 作者:行者123 更新时间:2023-12-02 09:06:09 24 4
gpt4 key购买 nike

考虑以下矩阵:

M <- cbind(c("ID001", "ID003", "ID002", "ID002", "ID003"),
c("BK101", "BK145", "BK101", "BK125", "BK101"),
c(6, 3, 2, 7, 3))

我想 reshape 矩阵,所以我得到以下矩阵:

       BK101 BK125 BK145
ID001 6 0 0
ID002 2 7 0
ID003 3 0 3

我尝试过:

reshape(M, idvar=[,1], timevar=[,2])

但这不起作用。

最佳答案

如果您为列命名并将它们放入数据框中:

M <- data.frame("a"=c("ID001","ID003","ID002","ID002","ID003"),
"b"=c("BK101","BK145","BK101","BK125","BK101"),
"c"=c(6,3,2,7,3))
xtabs(c~a+b,data=M)

b
a BK101 BK125 BK145
ID001 6 0 0
ID002 2 7 0
ID003 3 0 3

关于将R中矩阵中的二维数组的行 reshape 为列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58234015/

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