将稀疏矩阵扩展/转换为更大的稀疏矩阵

时间:2012-06-08 05:07:13

标签: r social-networking sparse-matrix

我知道这个问题的标题是混乱的,如果没有错的话。对不起,让我解释一下我尝试做的事情:

# I have a population of individuals:
population <- c("Adam", "Bob", "Chris", "Doug", "Emily", "Frank", "George","Harry", "Isaac", "Jim", "Kyle", "Louis")
population_size <- length(population) # this is 12

# I then draw a sample from this population
mysample_size <- 5
mysample <- sample(population,mysample_size, replace=FALSE)

# I then simulate a network among the people in the sample
frn <- matrix(rbinom(mysample_size*mysample_size, 1, 0.4),nrow=n)
x[x<=0] <- 0
x[x>0] <- 1
rownames(frn) <- mysample 
colnames(frn) <- mysample

*我现在想将值从frn转移到包含原始总体中所有成员的矩阵,即12乘12矩阵。该矩阵中的值仅来自frn 5 * 5矩阵。

我不知道如何在顶部的矩阵底部生成矩阵。

我已经考虑过不同的方式(例如使用iGraph并通过边缘列表推进)或运行循环,但实际上没有一种替代方法可以运行。知道背景可能很重要:我的实际矩阵比这要大很多,我需要多次运行这个操作,因此一个有效的解决方案会很棒。非常感谢你的帮助。

3 个答案:

答案 0 :(得分:0)

# create an empty matrix with NAs. You may have the full matrix already.
full_matrix <- matrix(rep(NA, population_size*population_size), nrow=population_size)
rownames(full_matrix) <- colnames(full_matrix) <- population
frn <- matrix(rbinom(mysample_size*mysample_size, 1, 0.4), nrow = mysample_size)
rownames(frn) <- colnames(frn) <- mysample
# Find the locations where they match
tmp <- match(rownames(frn), rownames(full_matrix))
tmp2 <- match(colnames(frn), colnames(full_matrix))

# do a merge
full_matrix[tmp,tmp2] <- frn

答案 1 :(得分:0)

最新解决方案:ind = match(mysample,population)为您提供与示例对应的行和列的索引号,因此请执行popn更新填充网络矩阵popn[ind,ind] = frn。完成。

答案 2 :(得分:0)

你可以使用......一个稀疏矩阵。

library(Matrix)
# Make sure the columns match
population <- c( mysample, setdiff(population, mysample) )
ij <- which( frn != 0, arr.ind=TRUE )
m <- sparseMatrix( 
  i = ij[,1], j=ij[,2], 
  x = 1,  # or frn[ij]
  dim = length(population)*c(1,1), 
  dimnames = list(population, population) 
)
m
相关问题