如何将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
相关产品推荐
相关产品推荐

