2012-06-08 345 views
1

我知道这个问题的标题是混乱的,如果没有错的。对不起,这一点,让我解释什么,我尝试做:扩展/稀疏矩阵转换成一个更大的稀疏矩阵

# 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并通过edgelists推进),或者运行循环,但并没有真正得到一个另类运行。也许很重要的背景知识:我的实际矩阵比这个大得多,我需要多次运行这个操作,因此一个有效的解决方案会很好。非常感谢你的帮助。

+1

什么是'x',它是如何适合这里的? 'nrow = n'中的'n'应该是'nrow = mysample_size',对吧? – Maiasaura

+0

感谢您的编辑。你是对的。它应该是“nrow = mysample_size” 就必须使FRN来替换x。我的错。抱歉。感谢您的关注 – chiron1979

回答

0

最巧妙的解决方案:ind = match(mysample,population)给你的行和对应于样品列的索引号,这样做popn[ind,ind] = frn更新人口网络矩阵popn。完成。

+0

这个工作。这似乎太简单了,但它似乎正是我所需要的。真的很酷。非常感谢。 – chiron1979

+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 
+0

这个工作。非常感谢您的支持。真的很感激它。 – chiron1979

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 
+0

*您可能* ......但会是什么优势超过直接这样做呢? –

+0

如果矩阵很小,没有优势,但如果它们更大,更稀疏,则更具有内存效率。 –

+0

很酷。非常感谢。这也是有效的(我已经开始看Tim的解决方案)。总而言之,它在显示m时禁止显示名称。不知道为什么。 – chiron1979