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

如何将data.frame反熔铸为矩阵?附具体实例需求

将DataFrame重塑为指定格式的矩阵

现有如下R数据框:

sources <- c("a", "b", "c", "a", "a", "b")
targets <- c("f", "v", "w", "a", "b", "c")
values <- c(12, 34, 56, 3, 76, 35)
df <- data.frame(sources, targets, values)

数据框内容:

sources targets values
1       a       f     12
2       b       v     34
3       c       w     56
4       a       a      3
5       a       b     76
6       b       c     35

需要将其转换为以sources取值为行名、targets取值为列名的矩阵,交叉单元格填充对应values值,无对应值的位置填0,最终得到如下3×6的矩阵:

f  v  w  a  b  c
a  12  0  0  3  76  0
b   0 34  0  0   0 35
c   0  0 56  0   0  0

方法1:使用tidyr包的pivot_wider

# 首次使用需安装包
install.packages("tidyr")
library(tidyr)

# 重塑数据并转换为矩阵
result_df <- pivot_wider(df, 
                         id_cols = sources, 
                         names_from = targets, 
                         values_from = values, 
                         values_fill = 0)
result_matrix <- as.matrix(result_df[,-1])
rownames(result_matrix) <- result_df$sources
# 调整列顺序匹配示例要求
result_matrix <- result_matrix[, c("f", "v", "w", "a", "b", "c")]

print(result_matrix)

方法2:使用基础R的xtabs函数

无需额外安装包,基础R自带函数即可实现:

# 生成交叉表并转为矩阵
result_matrix <- as.matrix(xtabs(values ~ sources + targets, data = df))
# 调整列顺序匹配示例
result_matrix <- result_matrix[, c("f", "v", "w", "a", "b", "c")]

print(result_matrix)

方法3:使用reshape2包的dcast

# 首次使用需安装包
install.packages("reshape2")
library(reshape2)

# 重塑数据并转换为矩阵
result_df <- dcast(df, sources ~ targets, value.var = "values", fill = 0)
result_matrix <- as.matrix(result_df[,-1])
rownames(result_matrix) <- result_df$sources
result_matrix <- result_matrix[, c("f", "v", "w", "a", "b", "c")]

print(result_matrix)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 04:12:09