You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用R语言的pivot_wider将三列数据转换为距离矩阵?

解决方案

你可以通过以下步骤将数据框转换为目标矩阵,并设置对角线值为100:

方法一:使用tidyr包(推荐)

# 若未安装tidyr包,先运行 install.packages("tidyr")
library(tidyr)

# 将长格式数据转换为宽格式
wide_df <- pivot_wider(demo_data, id_cols = query, names_from = target, values_from = dist)

# 设置行名为query列的值,移除原query列
rownames(wide_df) <- wide_df$query
wide_df <- wide_df[, -1]

# 转换为矩阵格式
dist_matrix <- as.matrix(wide_df)

# 将矩阵对角线值统一设为100
diag(dist_matrix) <- 100

# 查看最终矩阵
dist_matrix

方法二:使用Base R(无需额外包)

# 用Base R内置函数转换宽格式
wide_df_base <- reshape(demo_data, idvar = "query", timevar = "target", direction = "wide")

# 处理行名和列名
rownames(wide_df_base) <- wide_df_base$query
wide_df_base <- wide_df_base[, -1]
colnames(wide_df_base) <- sub("dist\\.", "", colnames(wide_df_base))

# 转矩阵并设置对角线
dist_matrix_base <- as.matrix(wide_df_base)
diag(dist_matrix_base) <- 100

# 查看结果
dist_matrix_base

运行代码后,你会得到符合要求的矩阵:对角线所有单元格值为100,其余单元格保留原dist列的对应数值。

内容的提问来源于stack exchange,提问作者Valentin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 14:13:31