-1

I have a loop where I want to do several calculations for different samples and save the results for each sample. These samples are for each loop different. I want to use the "i" in the loop to cut the samples.

So for instance:

  • In loop 1 (i=1), I have a sample from 0-1 and a sample from 1-100.
  • In loop 2 (i=2), I have a sample from 0-2 and a sample from 2-100.
  • In loop 99 (i=99), I have a sample from 0-99 and a sample from 99-100.

I built the following function, but there is a problem with the cut2 function since it doesn't recognize the "i". Outside the lapply loop it works, but not inside the loop.

    d=data.frame(MEt_Rainfed=rep(0,100),MEp_Rainfed=rep(0,100),MEt_Irrigation=rep(0,100),MEp_Irrigation=rep(0,100))

    o<-lapply(0:100, function(i){

        Alldata$irri=cut2(Alldata$irrigation,i)
        levels(Alldata$irri)<-c("0","1")

       Alldata_Rainfed<-subset(Alldata, irri == 0)
       Alldata_Irrigation<-subset(Alldata, irri == 1)

    #calculations per sample, then store all the values per i and per variable in a dataframe: (the calculations are not shown in this example)

     d[i, ] = c(MEt_Rainfed,MEp_Rainfed,MEt_Irrigation,MEp_Irrigation)

   })

   out<-as.data.frame(do.call(rbind, o))
user33125
  • 197
  • 1
  • 3
  • 12
  • Is the function `cut2` in a package? Or did you define it yourself? You're more likely to get a helpful answer if you include the code that's giving you trouble in a minimal, reproducible example. See http://stackoverflow.com/q/5963269 for help making such an example. – BenBarnes Aug 11 '15 at 13:47
  • @BenBarnes , the function cut2 comes from library(Hmisc). I consider this example as 'minimal' given the fact that the original code is much longer. Though, I will add a reproducible example. Thanks for your comment. – user33125 Aug 11 '15 at 14:33

1 Answers1

0

I am still not sure what went wrong in the previous example. However, I solved it in an alternative way:

o<-lapply(1:99, function(i){
Alldata_Rainfed<-subset(Alldata, irrigation <= i)
Alldata_Irrigation<-subset(Alldata, irrigation > i)
d[i, ] = c(MEt_Rainfed,MEp_Rainfed,MEt_Irrigation,MEp_Irrigation)

})

It is worthwhile noticing that the loop also should not go from 0-100 given the fact that this was exactly the range from the variable.

user33125
  • 197
  • 1
  • 3
  • 12