【问题标题】:Fill numerical values into empty cells of a matrix by dyad ID [duplicate]通过 dyad ID 将数值填充到矩阵的空单元格中
【发布时间】:2020-07-20 11:02:29
【问题描述】:

我正在处理一些双边贸易数据,每一行都包含出口商和进口商的 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)?

【问题讨论】:

    标签: r matrix cell


    【解决方案1】:

    尝试使用来自tidyrcompletepivot_wider

    library(tidyr)
    
    mat %>%
      complete(pid = unique(id), rid = unique(id)) %>%
      pivot_wider(names_from = pid, values_from = TradeValue)
    

    【讨论】:

    • 感谢您的提醒,但这段代码创建了一个 15605 x 165 的数据帧(或 tbl),而不是真正的 161 x 161 的填充交易值的矩阵。
    • @ChrisT。如果我将上述代码用于您共享的数据集,我会得到 161 X 162 数据帧。第一列是rid。此外,所有 ids 都存在于 mat 中,因此 mat %&gt;% pivot_wider(names_from = pid, values_from = TradeValue) 返回相同的内容。对于共享的数据,您还有其他收获吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-04
    • 2016-05-01
    • 2014-07-01
    相关资源
    最近更新 更多