获取分类数据频率矩阵的程序
Program to obtain frequency matrix of categorical data
我正在处理包含 300 多个分类特征的数据,我已将这些特征分解为 0 和 1。
现在,我需要创建一个特征矩阵,以在每个单元格中联合出现的频率。
最后,我希望创建此频率矩阵的热图。
因此,我在 R 中的数据框如下所示:
id cat1 cat2 cat3 cat4
156 0 0 1 1
465 1 1 1 0
573 0 1 1 0
我想要的输出是:
cat1 cat2 cat3 ...
cat1 0 1 0
cat2 1 0 2
cat3 1 2 0
.
.
其中每个单元格值表示两个分类变量一起出现的次数。
我们可以使用outer
#Since we have only 0's and 1's in column we can directly use &
fun <- function(x, y) sum(df[, x] & df[, y])
#Get all the cat columns
n <- seq_along(df)[-1]
#Apply function to every combination of columns
mat <- outer(n, n, Vectorize(fun))
#Turn diagonals to 0
diag(mat) <- 0
#Assign rownames and column names
dimnames(mat) <- list(names(df)[n], names(df[n]))
# cat1 cat2 cat3 cat4
#cat1 0 1 1 0
#cat2 1 0 2 0
#cat3 1 2 0 1
#cat4 0 0 1 0
我们可以使用 table
和 base R
中的 crossprod
i1 <- as.logical(unlist(df1[-1]))
out <- crossprod(table(df1$id[row(df1[-1])][i1],
names(df1)[-1][col(df1[-1])]. [i1]))
diag(out) <- 0
out
# cat1 cat2 cat3 cat4
# cat1 0 1 1 0
# cat2 1 0 2 0
# cat3 1 2 0 1
# cat4 0 0 1 0
数据
df1 <- structure(list(id = c(156L, 465L, 573L), cat1 = c(0L, 1L, 0L),
cat2 = c(0L, 1L, 1L), cat3 = c(1L, 1L, 1L), cat4 = c(1L,
0L, 0L)), class = "data.frame", row.names = c(NA, -3L))
我正在处理包含 300 多个分类特征的数据,我已将这些特征分解为 0 和 1。 现在,我需要创建一个特征矩阵,以在每个单元格中联合出现的频率。
最后,我希望创建此频率矩阵的热图。
因此,我在 R 中的数据框如下所示:
id cat1 cat2 cat3 cat4
156 0 0 1 1
465 1 1 1 0
573 0 1 1 0
我想要的输出是:
cat1 cat2 cat3 ...
cat1 0 1 0
cat2 1 0 2
cat3 1 2 0
.
.
其中每个单元格值表示两个分类变量一起出现的次数。
我们可以使用outer
#Since we have only 0's and 1's in column we can directly use &
fun <- function(x, y) sum(df[, x] & df[, y])
#Get all the cat columns
n <- seq_along(df)[-1]
#Apply function to every combination of columns
mat <- outer(n, n, Vectorize(fun))
#Turn diagonals to 0
diag(mat) <- 0
#Assign rownames and column names
dimnames(mat) <- list(names(df)[n], names(df[n]))
# cat1 cat2 cat3 cat4
#cat1 0 1 1 0
#cat2 1 0 2 0
#cat3 1 2 0 1
#cat4 0 0 1 0
我们可以使用 table
和 base R
crossprod
i1 <- as.logical(unlist(df1[-1]))
out <- crossprod(table(df1$id[row(df1[-1])][i1],
names(df1)[-1][col(df1[-1])]. [i1]))
diag(out) <- 0
out
# cat1 cat2 cat3 cat4
# cat1 0 1 1 0
# cat2 1 0 2 0
# cat3 1 2 0 1
# cat4 0 0 1 0
数据
df1 <- structure(list(id = c(156L, 465L, 573L), cat1 = c(0L, 1L, 0L),
cat2 = c(0L, 1L, 1L), cat3 = c(1L, 1L, 1L), cat4 = c(1L,
0L, 0L)), class = "data.frame", row.names = c(NA, -3L))