【问题标题】:Extending / converting a sparse matrix into a larger sparse matrix将稀疏矩阵扩展/转换为更大的稀疏矩阵
【发布时间】:2012-06-08 15:48:22
【问题描述】:

我知道这个问题的标题很混乱,如果没有错的话。对不起,让我解释一下我想做什么:

# 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 x 12 矩阵。该矩阵中的值仅来自 frn 5*5 矩阵。

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

我想过不同的方法(例如,使用 iGraph 和通过边缘列表推进)或运行循环,但并没有真正找到一个运行的替代方案。了解背景可能很重要:我的实际矩阵比这大得多,我需要多次运行此操作,因此一个有效的解决方案会很棒。非常感谢您的帮助。

【问题讨论】:

  • 什么是x 以及它如何适应这里?而nrow=n 中的n 应该是nrow=mysample_size,对吧?
  • 感谢您的编辑。你是对的。它应该是“nrow=mysample_size” 需要将 x 替换为 frn。我的错。对不起。感谢您的关注

标签: r social-networking sparse-matrix


【解决方案1】:

最简洁的解决方案:ind = match(mysample,population) 为您提供与样本对应的行和列的索引号,因此通过执行popn[ind,ind] = frn 来更新人口网络矩阵popn。完成。

【讨论】:

  • 这行得通。这似乎太简单了,但它似乎完全符合我的需要。真的很酷。非常感谢。
【解决方案2】:
# 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

【讨论】:

  • 这行得通。非常感谢您的支持。真的很感激。
【解决方案3】:

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

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

【讨论】:

  • 可以...但是比直接做有什么好处呢?
  • 如果矩阵那么小,则没有优势,但如果矩阵更大且稀疏,则内存效率更高。
  • 非常酷。非常感谢。这也有效(我已经开始研究 Tim 的解决方案)。总而言之,它在显示 m 时会抑制列名。不知道为什么。
  • 真的不喜欢因为这个原因而不必要地依赖外部包 - 总是有各种各样的奇怪和不一致。在我的书中,明智的第一步始终是看看是否有一种巧妙的方法可以解决手头的问题,而无需加载任何其他内容。
猜你喜欢
  • 2023-04-10
  • 2021-11-25
  • 2017-07-02
  • 2018-01-19
  • 2020-12-07
  • 2013-06-26
  • 1970-01-01
  • 1970-01-01
  • 2014-07-14
相关资源
最近更新 更多