2012-06-08 337 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