0
votes

My data is 2000 trap records (see head below). Each has a Season record attached to it. Season is set as a factor. I want to loop over all levels of Season ("Spring", "Summer", "Winter") and filter the data by each level for further analysis.

> head(DOC_data)
  X         project TrapType     Trap1     Trap2 DateChecked  BaitedWith
1 1 Whirinaki River        7 Still Set Still Set  2015-12-15 Erayz / Egg
2 2 Whirinaki River        7 Still Set Still Set  2015-12-15 Erayz / Egg
3 3 Whirinaki River        7 Still Set Still Set  2015-12-15 Erayz / Egg
4 4 Whirinaki River        7 Still Set Still Set  2015-12-15 Erayz / Egg
5 5 Whirinaki River        7 Still Set Still Set  2015-12-15 Erayz / Egg
6 6 Whirinaki River        7 Still Set Still Set  2015-12-15 Erayz / Egg
    BaitedOn Status   TrapTypeText                  TrapID       x       y
1 2015-12-15   Open DOC 200 Double Whirinaki RiverLine 611 1922039 5709247
2 2015-12-15   Open DOC 200 Double Whirinaki RiverLine 612 1922112 5709188
3 2015-12-15   Open DOC 200 Double  Whirinaki RiverLine 91 1920547 5707391
4 2015-12-15   Open DOC 200 Double  Whirinaki RiverLine 92 1920519 5707480
5 2015-12-15   Open DOC 200 Double  Whirinaki RiverLine 93 1920489 5707584
6 2015-12-15   Open DOC 200 Double  Whirinaki RiverLine 94 1920469 5707672
  Season Year        Region N_S
1 Summer 2015 Bay of Plenty   N
2 Summer 2015 Bay of Plenty   N
3 Summer 2015 Bay of Plenty   N
4 Summer 2015 Bay of Plenty   N
5 Summer 2015 Bay of Plenty   N
6 Summer 2015 Bay of Plenty   N

I have only included the loop to filter the data (below) because this is the point where it does not work. In my analysis I actually have further lines following on from the filter to analyse the subset of data. I have had this seasonal filter working previously with other data so I cannot understand where my error lies. The output produced at the moment is an empty dataframe where data should be.

for (y in levels(DOC_data$Season)){
  QEP_subset_year1 <- DOC_data %>% filter(Season == y)
  }
1
You may be better to use group_by(Season). What is the end goal - akrun
Although this is a possibility, I am interested in knowing what the problem could be with the current code I have. In my analysis I am actually looping across 4 factors and for 2 of the factors this code does what I want, and for 2 it doesn't. - patch105
updating same object seems to be an issue - akrun
Also you can check if there are leading/lagging spaces as == checks for exact match - akrun
Yes I made sure of that a bit earlier: levels(DOC_data$Season) <- trimws(levels(DOC_data$Season)) - patch105

1 Answers

0
votes

The problem was that I was using 'y' in my loop which must be a no-go. 'x' is the same. Changed to i and all is fine.

for (i in levels(DOC_data$Season)){
  QEP_subset_year1 <- DOC_data %>% filter(Season == i)
  }