Hello R-universe...

I am having trouble writing a function which contains a loop so I can sapply() 
it to a list of data frames

Each data frame has 241 observations of 15 variables. My loop takes a random 
sample of one row until the 40 consecutive rows after the sample have a 
d2p(variable) sum greater than 5.

here is my loop code (it works fine when applied to a 241 observation data 
frame):

        n<-241
        test<-0
        while(test<5){
                i<-sample(1:n-40,1)
                x<-my.data.frame[seq(from=i, to=i+40),]
                test<-sumx[,"d2p"],na.rm=TRUE)
                }; i ; test

I need this loop to be applied to EACH DATA FRAME in a list of 360 data frames 
created by splitting my master data frame, d, by each fish number. (contains 
observations for 360 fish, each with 241 observations of 15 variables).

        split.df<-split(d,d$fish)

I'm kind of new at writing functions, so I'm sure this probably doesn't make 
much sense, but here is what I tried for the function:

        samp.func<-function(f) {
        n<-241
        test<-0
        while(test<5){
                i<-sample(1:n-40,1)
                x<-f[seq(from=i, to=i+40),]
                test<-sum(x[,"d2p"],na.rm=TRUE)
                }}

and then tried to apply it to my list of data frames (NOT WORKING):

        sapply(split.df,samp.func)

I'm pretty sure I'm missing some way to instruct that I want the loop to cycle 
through for each item (data frame) in my split.df list. I've tried to play 
around with including "for" loops with no avail...

any ideas?



here is code for a simplified mock single-fish data frame (i.e. one item in my 
split.df list) to plug into the loop if you want to try it. 

fish<-rep(1,241)
d2p<-seq((50/241),50,(50/241))
my.data.frame<-data.frame(fish,d2p)

thanks!!
Sean


        [[alternative HTML version deleted]]

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to