模拟R中的共现数据

时间:2014-02-07 00:01:07

标签: r dataset cluster-analysis simulation

我正在尝试创建共生数据的数据集,其中感兴趣的变量是软件应用程序,我想模拟n×n矩阵,其中每个单元格的数字表示应用程序A的次数与应用程序B一起使用。如何在 R 中创建可用于测试一组聚类和分区算法的数据集。我将使用什么模型以及如何在 R 中生成数据?

2 个答案:

答案 0 :(得分:1)

n    <- 10
apps <- LETTERS[1:n]
data <- matrix(0,n,n)
rownames(data) <- apps
colnames(data) <- apps

# create artificial clusters
data[1:3,1:5] <- matrix(sample(3:5,15,replace=T),3,5)
data[6:9,4:8] <- matrix(sample(1:3,20,replace=T),4,5)

# clustering
hc <- hclust(dist(data))
plot(hc)
rect.hclust(hc, k=2)

注意:此答案已经过编辑,以反映共生矩阵必须是对称的事实。

答案 1 :(得分:1)

set.seed(42)
# software names:
software <- c("a","b","c","d")
# times each software used:
times.each.sw <- c(5,10,12,3)

# co-occurrence data.frame
swdf <- setNames(data.frame(t(combn(software,2))),c("sw1","sw2"))
swdf$freq.cooc <- apply(combn(times.each.sw,2),2,function(x) sample(1:min(x),1) )
#  sw1 sw2 freq.cooc
#1   a   b         5
#2   a   c         5
#3   a   d         1
#4   b   c         9
#5   b   d         2
#6   c   d         2

如果您更喜欢共现矩阵,那么这样的事情可能是:

mat <- diag(times.each.sw) 
dimnames(mat) <- list(software,software)
mat[lower.tri(mat)] <- swdf$freq.cooc
mat[upper.tri(mat)] <- t(mat)[upper.tri(mat)]

#  a  b  c d
#a 5  5  5 1
#b 5 10  9 2
#c 5  9 12 2
#d 1  2  2 3

对角线包含每个软件的使用次数(即与自身一起使用)。下/上三角形将包含每个组合的使用次数,它总是必须等于或小于使用该组的频率较低的次数。