基于二进制变量创建邻接矩阵

时间:2017-07-07 09:30:15

标签: r adjacency-matrix

我有一个data.frame,有两列。一个指示对象,另一个指示对象是否在某个组内。如何在不编写循环的情况下创建邻接矩阵?

data("mtcars")
testdf <- data.frame(names=as.character(row.names(mtcars)[1:5]),
                 ingroup=0)

set.seed(123)
testdf$ingroup[testdf$names%in%row.names(mtcars)[sample(length(row.names(mtcars)[1:5]), 2)]] <- 1

testdf
              names ingroup
1         Mazda RX4       0
2     Mazda RX4 Wag       1
3        Datsun 710       0
4    Hornet 4 Drive       1
5 Hornet Sportabout       0

编辑:所需的输出应该是一个矩阵,表明对象是否属于某个组:

data.frame(x1=c(0,0,0,0,0),
       x2=c(0,1,0,0,1),
       x3=c(0,0,0,0,0),
       x4=c(0,0,0,0,0),
       x5=c(0,1,0,0,1))
colnames(output) <- c("Datsun 710", "Hornet 4 Drive", "Hornet Sportabout", "Mazda RX4","Mazda RX4 Wag")
rownames(output) <- c("Datsun 710", "Hornet 4 Drive", "Hornet Sportabout", "Mazda RX4","Mazda RX4 Wag")

output
                  Datsun 710 Hornet 4 Drive Hornet Sportabout Mazda RX4 Mazda RX4 Wag
Datsun 710                 0              0                 0         0             0
Hornet 4 Drive             0              1                 0         0             1
Hornet Sportabout          0              0                 0         0             0
Mazda RX4                  0              0                 0         0             0
Mazda RX4 Wag              0              1                 0         0             1

谢谢, 托马斯

1 个答案:

答案 0 :(得分:0)

您只需获取ingroup变量的叉号:

res <- tcrossprod(testdf$ingroup)
rownames(res) <- testdf$names
colnames(res) <- testdf$names
res

# Mazda RX4 Mazda RX4 Wag Datsun 710 Hornet 4 Drive Hornet Sportabout
# Mazda RX4                 0             0          0              0                 0
# Mazda RX4 Wag             0             1          0              1                 0
# Datsun 710                0             0          0              0                 0
# Hornet 4 Drive            0             1          0              1                 0
# Hornet Sportabout         0             0          0              0                 0