假设您将 data.frames 存储在列表中。这是一些示例数据
t1<-structure(list(countryA = structure(c(1L, 1L, 1L, 2L, 3L, 4L), .Label = c("AUH",
"BOL", "BRA", "PAR"), class = "factor"), countryB = structure(c(2L,
4L, 5L, 3L, 1L, 5L), .Label = c("ARG", "GMY", "PER", "RUS", "UKG"
), class = "factor"), tie = c(2L, 1L, 4L, 5L, 1L, 4L)), .Names = c("countryA",
"countryB", "tie"), class = "data.frame", row.names = c(NA, -6L
))
t2<-structure(list(countryA = structure(1:6, .Label = c("ARG", "AUH",
"BOL", "BRA", "PAR", "RUS"), class = "factor"), countryB = structure(c(2L,
4L, 3L, 1L, 4L, 4L), .Label = c("ARG", "AUH", "PER", "UKG"), class = "factor"),
tie = c(1L, 4L, 5L, 1L, 4L, 2L)), .Names = c("countryA",
"countryB", "tie"), class = "data.frame", row.names = c(NA, -6L
))
tt<-list(t1=t1, t2=t2)
首先,您想获取所有唯一国家/地区名称的列表
countries <- sort(unique(unlist(sapply(tt, function(x) sapply(x[,1:2], levels)))))
现在,您要确保所有 data.frames 对国家列使用相同的因子水平。我们可以做到这一点
ttx <- lapply(tt, function(x) {x[,1:2]<-lapply(x[,1:2], factor, levels= countries); x})
现在他们都知道所有国家/地区,我们可以使用xtabs
加权关系值创建邻接矩阵
lapply(ttx, function(x) xtabs(tie~countryA+countryB, x))
这导致
$t1
countryB
countryA ARG AUH BOL BRA GMY PAR PER RUS UKG
ARG 0 0 0 0 0 0 0 0 0
AUH 0 0 0 0 2 0 0 1 4
BOL 0 0 0 0 0 0 5 0 0
BRA 1 0 0 0 0 0 0 0 0
GMY 0 0 0 0 0 0 0 0 0
PAR 0 0 0 0 0 0 0 0 4
PER 0 0 0 0 0 0 0 0 0
RUS 0 0 0 0 0 0 0 0 0
UKG 0 0 0 0 0 0 0 0 0
$t2
countryB
countryA ARG AUH BOL BRA GMY PAR PER RUS UKG
ARG 0 1 0 0 0 0 0 0 0
AUH 0 0 0 0 0 0 0 0 4
BOL 0 0 0 0 0 0 5 0 0
BRA 1 0 0 0 0 0 0 0 0
GMY 0 0 0 0 0 0 0 0 0
PAR 0 0 0 0 0 0 0 0 4
PER 0 0 0 0 0 0 0 0 0
RUS 0 0 0 0 0 0 0 0 2
UKG 0 0 0 0 0 0 0 0 0
然后你可以做任何你喜欢的事情。即使缺少一些观察结果,让它们都使用相同的因子水平以获得具有相同维度的表格非常重要。