1

I am a beginner at R. I'm trying to create a for loop for a huge dataframe where I will be applying many different functions. However, the very first part of the for loop function is not working the way I want it to and I am wondering if anyone can tell me what it is I am doing wrong.

The data frame I am working with is called allbr_demo_noEPP and it has 14 columns and one of those columns is called "Year". What I am trying to do is first subset this data frame by specific years. I am looking at the years 2000 - 2013. I want to first subset the dataframe by the year 2000 then do a whole bunch of other functions on the subsetted dataframe, and then do it all over again for the year 2001, etc.

The code I wrote was:

    for(i in c(2000:2013)) {
      allbr_demo_noEPP_year <- subset(allbr_demo_noEPP, Year == "i")
      allbr_demo_noEPP_year_geno <- allbr_demo_noEPP_year[allbr_demo_noEPP_year$Pairs %in% c(genome$pair1,genome$pair2),]
      allbr_demo_noEPP_year_geno$relatedness <- laply(allbr_demo_noEPP_year_geno$Pairs, function(x) genome[genome$pair1==x|genome$pair2==x,'PI_HAT'])}

For some reason the allbr_demo_noEPP_year data frame has 0 observations. I'm not sure what I am doing wrong. Is this not how you use for loops? Any help will be very much appreciated, thank you!

Prradep
  • 5,506
  • 5
  • 43
  • 84
Jennifer Diamond
  • 113
  • 2
  • 11
  • 5
    Hi Jennifer, Welcome to Stack Overflow. Please have a look at [How to make a great R reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) so that it is easy for others to help you. BTW, the first line in the for loop should be `subset(allbr_demo_noEPP, Year == i)` – Ronak Shah May 19 '17 at 01:46
  • For one thing, you are overwriting all your objects with each iteration. If you are interested in a base R solution, look into `split` and `lapply` to first split your data.frame into subsets based on a factor and then apply a function/several functions to each part. – Taylor H May 19 '17 at 01:51

0 Answers0