Reputation: 79
I've B1
, B2
, B3
, etc as igraph
objects.
This is my code:
setwd("D:\\Educacion\\PeerEffects\\matriz de contactos\\Intentos\\")
filenames <- list.files(path=getwd(),pattern="matriz+.*dta")
list(filenames)
names <-substr(filenames,1,7)
for(i in names)
{
filepath <- file.path("D:/Educacion/PeerEffects/matriz de contactos/Intentos",paste(i,".dta",sep=""))
assign(i, read.dta(filepath))
}
for (i in 1:length(names)){
assign(paste0("A", i), unname(as.matrix(get(paste0("matriz", i)))))
assign(paste0("B", i), graph.adjacency(get(paste0("A", i)), mode = "directed", weighted = NULL, diag = FALSE))
}
This is what I need to do to every igraph objetc B1, B2, etc. where "matrices" should be the list of igraph objetcs:
for (i in matrices) {
average.path.length(i)
diameter(i)
transitivity(i)
degree(i)
}
This is the error I get when matrices is a list of names (B1, B2, etc): Error in average.path.length(i) : Not a graph object
Upvotes: 0
Views: 69
Reputation: 56905
To get the variable called 'matrix1', use get
m <- get(paste0('matrix', i))
Then do all your things like degree(m)
, ...
Though as I mentioned in your previous question, it would be better if matrices
was the list of igraph objects, rather than the list of names of the objects. Then your current code would work as-is, and you would have functions like lapply
available to you.
Update: re your assigning code.
You could do this many ways, but the common element is that instead of storing your variables in A1, ..., A100 , you store them in a list A
so that A[[1]]
is your old A1.
e.g.
As <- lapply(names,
function (name) {
filepath <- ...
as.matrix(read.dta(filepath)) # this is Ai
})
# note As[[i]] is your old Ai
Bs <- lapply(As, graph.adjacency, mode="directed", weighted = NULL, diag = FALSE)
# now Bs[[i]] is your old Bi
And you could do e.g.
avg.lengths <- lapply(Bs, average.path.length)
degree <- lapply(Bs, degree)
and so on. Then for graph i
you could use Bs[[i]]
to get the graph, avg.lengths[[i]]
to get the avg length, etc.
If average.path.length
, diameter
, transitivity
, and degree
all return SINGLE values, you could simply store them in a dataframe:
graph.properties <- data.frame(
graph=1:length(Bs),
average.path.length=sapply(Bs, average.path.length),
diameter=sapply(Bs, diameter),
...)
Then graph.properties$diameter[i]
is the diameter of Bi
. However you can't store the graphs themselves in a dataframe, as dataframe cells should contain single values only not complicated objects.
Also I think degree
returns a numeric vector, so you're stuck with a list rather than dataframe (hence my use of lapply
initially rather than sapply
).
Upvotes: 2