R - 如何将 2 个成对向量组合成矩阵 [英] R - How to combine 2 pairwise vectors into a matrix

查看:41
本文介绍了R - 如何将 2 个成对向量组合成矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于下表:

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 中实体对之间的相关性度量.

Where col3 is a correlation measure between pairs of entities in col1 and col2.

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

How can I construct a matrix for which the column names are col1, the row names are col2, and the values in the cells of the matrix are populated by col3?

推荐答案

需要一些数据来处理,所以我会补一些.

Need some data to work with so I'll make some up.

# Make fake data
x <- c('A','B','C')
dat <- expand.grid(x, x)
dat$Var3 <- rnorm(9)

我们可以使用基础 R 来做到这一点.我不太擅长重塑"功能,但您可以这样做.虽然之后需要清理列名

We can use base R to do this. I'm not very good with the 'reshape' function but you could do this. The column names would need to be cleaned up afterwards though

> reshape(dat, idvar = "Var1", timevar = "Var2", direction = "wide")
  Var1     Var3.A      Var3.B     Var3.C
1    A -1.2442937 -0.01132871 -0.5693153
2    B -1.6044295 -1.34907504  1.6778866
3    C  0.5393472 -1.00637345 -0.7694940

或者,您可以使用 reshape2 包中的 dcast 函数.我认为输出更干净一些.

Alternatively you could use the dcast function from the reshape2 package. The output is a little cleaner I think.

> library(reshape2)
> dcast(dat, Var1 ~ Var2, value.var = "Var3")
  Var1          A           B          C
1    A -1.2442937 -0.01132871 -0.5693153
2    B -1.6044295 -1.34907504  1.6778866
3    C  0.5393472 -1.00637345 -0.7694940

这篇关于R - 如何将 2 个成对向量组合成矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆