oop - Array / List / collection of objects of a class in R -


i beginner oop in r , stuck @ problem can find no solution.

i defined class "node" in r using setclass contains information "node" in network -

setclass(class = "node",      representation = representation(nid = "integer", links = "integer",          capacity = "numeric"),      prototype = prototype(nid = integer(1), links = integer(20),          capacity = numeric(20))) 

what want create array/list holds several "nodes", each of of class "node". like

nodeid[100] <- new("node") 

but doesnt work. have tried creating arrays , converting class "node" didnt either.

this me things loop on nodes in system-

for(i in 1:dim(nodeid)) {     nodeid[i]@capacity <- 1000     blah blah.... } 

note problem isnt initializing/defaulting value of slots (e.g. capacity in case). can that. appreciate.

thanks,

sumit

answer ----

thanks @ricardo , @dickoa. created list of nodeid wanted .

want add else facing same problem in order access elements/slots of list of class "node" have use following:

nodeid[[1]]@capacity[1] 

also, use lapply instead of for.

sumit

try using replicate

nodeid <- replicate(100, new("node"), simplify="list") is(nodeid) # [1] "list"   "vector" is(nodeid[[1]]) # [1] "node" 

using nodeid[100] <- new("node") found, not work. (is attempting) object called nodeid , if found, try set 100th element new("node"). not, say, create object nodeid , populate 100 elements.


also, notice can avoid for loop instead using, say, lapply: eg, instead of:

for(i in 1:dim(nodeid)) {  nodeid[i]@capacity <- 1000  blah blah.... } 

use:

lapply(nodeid, function(n) {blah balh...} ) 

Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

html - Unable to style the color of bullets in a list -

c# - must be a non-abstract type with a public parameterless constructor in redis -