gpt4 book ai didi

r - 从数据框创建方阵

转载 作者:行者123 更新时间:2023-12-04 17:15:55 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Reconstruct symmetric matrix from values in long-form

(5 个回答)


4年前关闭。




我无法从我的 data.frame 制作方阵。
现在我的数据看起来像这样:

  var1 var2 value
A B 4
C D 5
D A 2
B D 1

我正在尝试将 data.frame 转换为如下所示的矩阵:
    A    B    C   D
A 0 4 0 2
B 4 0 0 1
C 0 0 0 5
D 2 1 5 0

我尝试了 R 中可用的不同包中的许多功能,但仍然找不到解决方案。

最佳答案

这是在字符向量上使用矩阵索引的基本 R 方法。

## set up storage matrix
# get names for row and columns
nameVals <- sort(unique(unlist(dat[1:2])))
# construct 0 matrix of correct dimensions with row and column names
myMat <- matrix(0, length(nameVals), length(nameVals), dimnames = list(nameVals, nameVals))

# fill in the matrix with matrix indexing on row and column names
myMat[as.matrix(dat[c("var1", "var2")])] <- dat[["value"]]

这返回
myMat
A B C D
A 0 4 0 0
B 0 0 0 1
C 0 0 0 5
D 2 0 0 0

有关这种强大的索引形式如何工作的详细信息,请参阅帮助文件 ?"[" 的矩阵和数组部分。 .特别是,本节的第四段讨论了这种形式的索引。

请注意,我假设前两个变量是字符向量而不是因子。这使它更容易一些,因为我不必使用 as.character来胁迫他们。

要将结果转换为 data.frame,只需将上述代码包装在 as.data.frame 中功能。

数据
dat <- 
structure(list(var1 = c("A", "C", "D", "B"), var2 = c("B", "D",
"A", "D"), value = c(4L, 5L, 2L, 1L)), .Names = c("var1", "var2",
"value"), class = "data.frame", row.names = c(NA, -4L))

关于r - 从数据框创建方阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46562173/

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