【问题标题】:Create an adjacency matrix of three variables with dplyr in R在 R 中使用 dplyr 创建三个变量的邻接矩阵
【发布时间】:2021-09-20 04:23:50
【问题描述】:

周五晚上,我正在努力解决这个问题。 我的数据是这样的

df <- data.frame(teamA=c("Italy","Italy","England","England"),
                 teamB=c("Germany","Greece","Germany","Greece"), win=c(0,1,1,1))
df
    teamA   teamB win
1   Italy Germany   0
2   Italy  Greece   1
3 England Germany   1
4 England  Greece   1

我想把它转换成一个像这样的矩阵。最好使用 dplyr,但我很绝望,没关系

         Italy   England 
Germany  0         1

Greece   1         1

【问题讨论】:

    标签: r matrix dplyr aggregate tidyverse


    【解决方案1】:

    尝试使用 base R 中的 xtabs 并将属性设置为 NULL(不需要包)

    out <- xtabs(win ~ teamB + teamA, df)
    names(dimnames(out)) <- NULL
    

    【讨论】:

    • 我找不到比xtabs 更简单的解决方案,已经投票了:)!
    【解决方案2】:

    igraph 的选项

    graph_from_data_frame(df) %>%
        set_vertex_attr(name = "type", value = names(V(.)) %in% df$teamA) %>%
        as_incidence_matrix(attr = "win")
    

    给予

            Italy England
    Germany     0       1
    Greece      1       1
    

    【讨论】:

      【解决方案3】:

      使用pivot_wider -

      library(tidyverse)
      
      df %>%
        pivot_wider(names_from = teamA, values_from = win) %>%
        column_to_rownames('teamB') %>%
        as.matrix
      
      #.       Italy England
      #Germany     0       1
      #Greece      1       1
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-12-02
        • 2018-01-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多