问题
I am aware that the title of this question is confusing, if not wrong. Sorry for this, let me explain what I try to do:
# 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
*I would now like to transfer the values from frn into a matrix that includes all members from the original population, i.e. a 12 by 12 matrix. The values in that matrix would only come from the frn 5*5 matrix.
I do not know how to generate the matrix at the bottom from the matrix at the top.
I have thought of different ways (e.g. using iGraph and advancing via edgelists) or running loops, but did not really get a single alternative to run. Maybe important to know as background: My actual matrices are much larger than this and I need to run this operation many times, thus an efficient solution would be great. Thanks a lot for your help.
回答1:
Neatest solution: ind = match(mysample,population)
gives you the index numbers of the rows and columns corresponding to the sample, so update the population network matrix popn
by doing popn[ind,ind] = frn
. Done.
回答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:
You could use... a sparse matrix.
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
来源:https://stackoverflow.com/questions/10943338/extending-converting-a-sparse-matrix-into-a-larger-sparse-matrix