[R] Loop Help

Jim Lemon jim at bitwrit.com.au
Sun Jun 17 09:51:58 CEST 2012


On 06/17/2012 08:50 AM, @ngel wrote:
> Hello again and thank you all so much for the help. Well, I tried and did it
> myself, here's what I wrote:
>
> library(tnet)
> net<- read.table("data.txt")
> net<- as.tnet(net, type="longitudinal tnet")
>
> loop<- range(net[,1])
> net.static<- vector(length=as.integer(loop[2]-loop[1])+1, mode="list")
> j<- 1
> while(loop[1]<  loop[2]) {
> 	net.static[[j]]<- as.static.tnet(net[net[,"t"]<=loop[1],])
> 	degree<- degree_w(net.static[[j]])
> 	results[[j]]<- apply(degree, 2, mean)
> 	print(results[[j]])
> 	loop[1]<- loop[1]+(30*30*24)
> 	j<- j+1
> }
> max(loop[2]-loop[1])
>
> and... it actually works, BUT
> for every screenshot, it doesn't give the mean once, it prints it as many
> times as the raws of the screenshot!
> So if one screenshot has 3 lines, I get the result three times and then the
> following screenshot's result as many times as the raws it has! Trying to
> figure out why! Can somebody please help me?
>
> By the way, I did tried this:
>
> get_network_slices<-function(timestamps) {
>   nslices<-length(timestamps)
>   netslices<-list()
>   for(slice in 1:nslices) {
>   this_slice<- as.static.tnet(net[net[,"t"]<=as.POSIXlt(timestamps[slice],])
>   degree_w(this_slice)
>   netslices[[slice]]<-list(degree_w,apply(this_slice,2,mean))
>   }
>   return(netslices)
> }
>
> and got an error that this_slice is not defined!!!
>
Hi @ngel,
The error probably stems from me not getting the line that assigns a 
value to "this_slice" correct, so it fails and "this_slice" is not 
defined. I don't really know what that command is doing, and I have 
probably not gotten it quite right. Try just that line:

this_slice<-
  as.static.tnet(net[net[,"t"]<=as.POSIXlt(timestamps[slice],])

outside of the function, substituting a real value for 
"timestamps[slice]" and see what happens.

Jim



More information about the R-help mailing list