r - 通过 dyad ID 将数值填充到矩阵的空单元格中
问题描述
我正在处理一些双边贸易数据,每一行都包含出口商和进口商的 ID,以及他们的贸易额。然后,我想将每一行的交易金额映射到矩阵对象中其对应的单元格,该矩阵对象的 ID 为 "exporter" 和 "importer",分别列为 "row" 和 "column" dimnames
。
我想知道有什么更简单的方法可以做到这一点?以下是我当前的工作代码。
# import data
mat <- readRDS(url("https://www.dropbox.com/s/aj1607s975c5gf6/mat.rds?dl=1"))
head(mat, 10)
# import ID
id <- readRDS(url("https://www.dropbox.com/s/6weala2j0idb16i/id.rds?dl=1"))
# create matrix (there are a total of 161 possible IDs though not all of them appear on the data)
matrix <- matrix(rep( 0, len=161*161), nrow = 161)
dimnames(matrix) <- list(unique(id), unique(id))
# how can I fill the trade value (in mat[, 3]) into the corresponding cell on the matrix by match mat[, 1] and mat[, 3] on the dimnames(matrix)?
解决方案
尝试使用complete
和pivot_wider
从tidyr
.
library(tidyr)
mat %>%
complete(pid = unique(id), rid = unique(id)) %>%
pivot_wider(names_from = pid, values_from = TradeValue)
推荐阅读
- apache-camel - 如何替换 DefaultHeaderFilterStrategy
- sql - Teradata 中的 SAS 滞后和超前函数
- python - 根据索引在熊猫中制作多列
- r - R中的tryCatch:如何捕获传递给警告参数的函数中的所有警告消息?
- php - 如何将图像数组从一个 PHP 文件发送到另一个 PHP?
- aws-serverless - 无服务器:部署时无服务器错误
- mvvm - 通用 Windows 平台问题绑定中的 MVVM
- python - 在odoo中添加计算列
- cordova - 如何在 phonegap 中发送 HTTP 请求?
- php - Plesk 面板和新的 crm 程序