[R] sapply( ) a loop function
Daniel Malter
daniel at umd.edu
Fri Aug 12 00:20:27 CEST 2011
I am not sure what purpose the while loop has. However, the main problem
seems to be that you need to put:
i<-sample(1:(n-40),1) #This sample from 1 to n-40
rather than
i<-sample(1:n-40,1) #this samples one 1:n and then subtracts 40
Otherwise, you may get negative index values
Best,
Daniel
bignami83 wrote:
>
> 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 at 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.
>
--
View this message in context: http://r.789695.n4.nabble.com/sapply-a-loop-function-tp3737261p3737481.html
Sent from the R help mailing list archive at Nabble.com.
More information about the R-help
mailing list