【问题标题】:Run loop to build co-occurrence matrix运行循环以构建共现矩阵
【发布时间】:2014-10-26 02:43:12
【问题描述】:

我有以下数据框并希望:

(1) 构建一个 4x4 共现矩阵。

(2) 使用循环来运行它,因为我使用的是具有更多变量的更大数据集。

a <- rep(c("a", "a", "b", "c"), 4)
b <- rep(c("b", "c", "d", "d"), 4)
df <- data.frame(a,b)

out <- matrix(0, 
              nrow = 4, # how do I call just the levels?
              ncol = 4)
out

以下代码不起作用,但可能有助于有人帮助我解决这个问题。

for (i in 1:nrow(df)) {
  ind <- which(lvls == df[i, "a"]) 
  out[i, ind] <- 1 
}
out

# loop over variables in b
for (j in 1:nrow(df)) {
  ind <- which(lvls == df[j, "b"]) 
  out[j, ind] <- 1 
}
out

这是我希望的输出......

       [a]  [b]  [c]  [d]
[a]     0    4    4    0
[b]     4    0    0    4
[c]     4    0    0    4
[d]     0    4    4    0

任何帮助都会很棒。提前致谢!

【问题讨论】:

  • 请同时发布您的示例中所需的结果
  • @bpace 在提供的示例中,没有 ad 行,bc 相同。我不明白你是如何得到4 的。检查table(as.character(interaction(df, sep="")))的输出
  • 谢谢,@akrun ... 已修复。

标签: r matrix


【解决方案1】:

你可以试试

 lvls <- sort(as.character(unique(unlist(df))))
 df[] <- lapply(df, function(x) factor(x, levels=lvls) )
 m1 <- table(df)
 m1[lower.tri(m1)] <- m1[upper.tri(m1)]
 class(m1) <- "matrix"
 dimnames(m1) <- unname(dimnames(m1)) #as suggested by @Richard Scriven
 m1
 #    a b c d
 #  a 0 4 4 0
 #  b 4 0 0 4
 #  c 4 0 0 4
 #  d 0 4 4 0

更新

假设,如果您的数据发生更改(由@user20650 提供)

df[1, ] <- c("b", "a")
df[] <- lapply(df, function(x) factor(x, levels=lvls) )
m1 <- table(df)
m2 <- m1 + t(m1)
m2 #you can convert to class `matrix` and change the dimnames as above
#    b
#a b a c d
#b 0 4 0 4
#a 4 0 4 0
#c 0 4 0 4
#d 4 0 4 0

更新2

如果您不想要 symmetric 矩阵并希望拥有实际的 counts

 df[] <- lapply(df, function(x) factor(x, levels=lvls) )
 m1 <- table(df)
 indx <- !m1 & lower.tri(m1)
 m1[indx] <- m1[t(indx)]
 class(m1) <- "matrix"
 dimnames(m1) <- unname(dimnames(m1))
 m1
 #  b a c d
 #b 0 1 0 4
 #a 3 0 4 0
 #c 0 4 0 4
 #d 4 0 4 0

 table(as.character(interaction(df,sep="")))

 #ab ac ba bd cd 
 #3  4  1  4  4 

更新3

关于多个变量,我不确定预期的结果,也许这会有所帮助:

indx <- combn(colnames(df1),2)
res <- Reduce(`+`,lapply(split(indx, col(indx)), function(x) table(df1[x])))
dimnames(res) <- unname(dimnames(res))
res
#   a  b  c  d  e  f  g
#a  4  9  5  4  2  6  5
#b  8  6 13  6  5  9  3
#c  6  8  7  5  2  7  2
#d  4  3  5  6  2  2  6
#e  8  6  8 11  3  5  5
#f  4  4  3  5  2  1  4
#g  1  4  2  5  3  2  4

数据

a <- rep(c("a", "a", "b", "c"), 4)
b <- rep(c("b", "c", "d", "d"), 4)
df <- data.frame(a,b, stringsAsFactors=FALSE)

多列数据

 set.seed(24)
 df1 <- as.data.frame(matrix(sample(letters[1:7], 6*16, replace=TRUE), ncol=6))
 lvls1 <- sort(as.character(unique(unlist(df1))))
 df1[] <- lapply(df1, function(x) factor(x, levels=lvls1))

【讨论】:

    猜你喜欢
    • 2017-09-23
    • 1970-01-01
    • 1970-01-01
    • 2012-10-28
    • 2017-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多