【问题标题】:Matrix manipulation in Excel/RExcel/R 中的矩阵操作
【发布时间】:2019-03-19 11:56:16
【问题描述】:

我有一个非常大的邻接矩阵,格式如下,其中数字表示行中的每个人与列中的人获胜的次数。

Loser/Winner Steve Joe Chan Jess
       Steve   0    2   8    4
         Joe   8    0   2    5
        Chan   9    5   0    6
        Jess   4    6   9    0

我想将其转换为 R 或 Excel 中的净胜数矩阵。 因此,对于这个特定示例,输出将是:

Loser/Winner Steve Joe Chan Jess
       Steve   0   -6   -1    0
         Joe   6    0   -3   -1
        Chan   1    3    0   -3
        Jess   0    1    3    0

【问题讨论】:

  • 您能否以易于复制的格式提供您的数据,例如使用dput(mat)
  • 您已经将给定的矩阵存储在某个对象中,对吗?如果它的名字是matdput(mat) 应该提供一个复制粘贴友好的结构。您也可以使用datapasta 包。

标签: r excel matrix


【解决方案1】:

我认为它可以满足您的需求。

mat <- data.frame(stringsAsFactors=FALSE,
                  Loser_Winner = c("Steve", "Joe", "Chan", "Jess"),
                  Steve = c(0, 8, 9, 4),
                  Joe = c(2, 0, 5, 6),
                  Chan = c(8, 2, 0, 9),
                  Jess = c(4, 5, 6, 0))

win_matrix <- as.matrix(x = mat[, -1])
loss_matrix <- t(x = win_matrix)
net_win <- as.data.frame(x = (win_matrix - loss_matrix))

net_win
#>   Steve Joe Chan Jess
#> 1     0  -6   -1    0
#> 2     6   0   -3   -1
#> 3     1   3    0   -3
#> 4     0   1    3    0

reprex package (v0.2.1) 于 2019 年 3 月 19 日创建

【讨论】:

    【解决方案2】:

    如果您的数据已经是matrix 形式,这很简单

    mat - t(mat)
    #      Steve Joe Chan Jess
    #Steve     0  -6   -1    0
    #Joe       6   0   -3   -1
    #Chan      1   3    0   -3
    #Jess      0   1    3    0
    

    样本数据

    mat <- as.matrix(read.table(text =
        "Steve Joe Chan Jess
           Steve   0    2   8    4
             Joe   8    0   2    5
            Chan   9    5   0    6
            Jess   4    6   9    0", header = T))
    

    【讨论】:

    • 这和我的回答一样。
    • @yarnabrina 类似。我正在避免整个data.frame 过剩。由于 OP 具​​有邻接矩阵,因此无需使用 data.frames。对于较大的对象,使用矩阵(而不是data.frames)可以显着提高性能。由于这里的解决方案非常简单,因此应将重点放在干净和高性能的代码上。
    猜你喜欢
    • 1970-01-01
    • 2018-10-23
    • 2015-04-24
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 2020-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多