[R] Loop Help
Jim Lemon
jim at bitwrit.com.au
Sat Jun 16 11:09:26 CEST 2012
On 06/16/2012 07:41 AM, @ngel wrote:
> Hello all,
> I'm new here and new to R, but I have to admit I'm learning rather fast.
> Right now I need to write a loop, and I don't seem to think I'm doing it
> properly, judging by the errors I get! What I need to do is to insert my
> data (csv-table) into a variable, and take snapshots of my data (it's
> longtitudinal) and they 'play' with the snapshot. To give you an example:
>
> # I Load tnet the library I need
> library(tnet)
>
> # I Load my data
> net<- read.table("data.txt")
>
> # Check if net is tnet
> net<- as.tnet(net, type="longitudinal tnet")
>
> # And slice the data getting new variables for every day
> net.101031<- as.static.tnet(net[net[,"t"]<=as.POSIXlt("2010-10-31
> 00:00:00"),])
>
> # Then get the degree of the sliced network
> degree_w(net.101031)
>
> # and the mean of each column in the data.frame
> apply(net.101031, 2, mean)
>
> Now the problem is that there are way too many "days" to do it manually and
> I need to wrap this part:
>
>
> net.101031<- as.static.tnet(net[net[,"t"]<=as.POSIXlt("2010-10-31
> 00:00:00"),])
> degree_w(net.101031)
> apply(net.101031, 2, mean)
>
> in a loop, and print the results. But...
Hi @ngel,
It appears as though you want to return a nested list from your loop
that steps through a specified set of timestamps. Probably something
like 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)
}
This should return a list in which each element contains the degree
value and a list or vector of means.
Jim
More information about the R-help
mailing list