gpt4 book ai didi

R - 如何将 2 个成对向量组合成矩阵

转载 作者:行者123 更新时间:2023-12-05 00:28:39 25 4
gpt4 key购买 nike

鉴于下表:

X = 

col1 col2 col3
row1 "A" "A" "1.0"
row2 "A" "B" "0.9"
row3 "A" "C" "0.4"
row4 "B" "A" "0.9"
row5 "B" "B" "1.0"
row6 "B" "C" "0.2"
row7 "C" "A" "0.4"
row8 "C" "B" "0.2"
row9 "C" "C" "1.0"

其中 col3 是 col1 和 col2 中实体对之间的相关性度量。

如何构造列名称为 col1、行名称为 col2 且矩阵单元格中的值由 col3 填充的矩阵?

最佳答案

df <- read.table(textConnection('col1    col2    col3
row1 "A" "A" "1.0"
row2 "A" "B" "0.9"
row3 "A" "C" "0.4"
row4 "B" "A" "0.9"
row5 "B" "B" "1.0"
row6 "B" "C" "0.2"
row7 "C" "A" "0.4"
row8 "C" "B" "0.2"
row9 "C" "C" "1.0"'), header=T)

## fetch row/column indices
rows <- match(df$col1, LETTERS)
cols <- match(df$col2, LETTERS)

## create matrix
m <- matrix(0, nrow=max(rows), ncol=max(cols))

## fill matrix
m[cbind(rows, cols)] <- df$col3

m
# [,1] [,2] [,3]
#[1,] 1.0 0.9 0.4
#[2,] 0.9 1.0 0.2
#[3,] 0.4 0.2 1.0

关于R - 如何将 2 个成对向量组合成矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18560962/

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