在 R 中使用 dplyr 创建三个变量的邻接矩阵
Create an adjacency matrix of three variables with dplyr in R
周五晚上我正在仔细研究这个问题。
我的数据看起来像这样
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
尝试使用 base R
中的 xtabs
并将属性设置为 NULL(不需要包)
out <- xtabs(win ~ teamB + teamA, df)
names(dimnames(out)) <- NULL
选项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
使用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
周五晚上我正在仔细研究这个问题。 我的数据看起来像这样
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
尝试使用 base R
中的 xtabs
并将属性设置为 NULL(不需要包)
out <- xtabs(win ~ teamB + teamA, df)
names(dimnames(out)) <- NULL
选项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
使用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