Create a co-occurrence matrix from dummy-coded observations

后端 未结 1 1524
隐瞒了意图╮
隐瞒了意图╮ 2020-11-27 07:17

Is there a simple approach to converting a dataframe with dummies on whether an aspect is present, to a co-occurrence matrix containing the counts of two aspects co-occuring

相关标签:
1条回答
  • 2020-11-27 07:52

    This will do the trick:

    X <- as.matrix(X)
    out <- crossprod(X)  # Same as: t(X) %*% X
    diag(out) <- 0       # (b/c you don't count co-occurrences of an aspect with itself)
    out
    #      [,1] [,2] [,3] [,4]
    # [1,]    0    0    1    0
    # [2,]    0    0    2    1
    # [3,]    1    2    0    1
    # [4,]    0    1    1    0
    

    To get the results into a data.frame exactly like the one you showed, you can then do something like:

    nms <- paste("X", 1:4, sep="")
    dimnames(out) <- list(nms, nms)
    out <- as.data.frame(out)
    
    0 讨论(0)
提交回复
热议问题