Jordan
Jordan

Reputation: 13

Adding values to a column based on number of rows

I'm not really sure how to search for an answer to this question but I have a tibble that shows locations and seasons that those locations were surveyed. I need to add a column that states if that was the first, second, third, etc season for that location. Each location has a different season that was it's first season so I can't exactly base the new column on the year. Seasons also are not necessarily consecutive. I feel like there must be a way to count the number of rows in a group of rows and then assign each a different number.

Here is my example data:

> forest <- c("bhd", "bhd", "bhd", "flh", "hlc", "hlc", "hlc", "llo", "llo")
> season <- c("2017-2018", "2016-2017", "2015-2016", "2018-2019", "2019-2020",
+             "2016-2017", "2017-2018", "2019-2020", "2017-2018")
> example <- tibble(forest = forest, season = season)
> example
# A tibble: 9 x 2
  forest season   
  <chr>  <chr>    
1 bhd    2017-2018
2 bhd    2016-2017
3 bhd    2015-2016
4 flh    2018-2019
5 hlc    2019-2020
6 hlc    2016-2017
7 hlc    2017-2018
8 llo    2019-2020
9 llo    2017-2018

What I am hoping to have in the end:

# A tibble: 9 x 3
  forest season    rotation
  <chr>  <chr>     <chr>   
1 bhd    2017-2018 Third      
2 bhd    2016-2017 Second      
3 bhd    2015-2016 First      
4 flh    2018-2019 First      
5 hlc    2019-2020 Third      
6 hlc    2016-2017 First      
7 hlc    2017-2018 Second      
8 llo    2019-2020 Second      
9 llo    2017-2018 First

Any ideas on how to achieve this would be really helpful.

Upvotes: 1

Views: 43

Answers (2)

TarJae
TarJae

Reputation: 78917

library(dplyr)
example %>% 
  group_by(forest) %>% 
  dplyr::arrange(season, .by_group = TRUE) %>% 
  dplyr::mutate(rotation = row_number()) %>% 
  mutate(rotation = as.character(rotation)) %>% 
  mutate(rotation = case_when(rotation == 1 ~ "First",
                              rotation == 2 ~ "Second",
                              rotation == 3 ~ "Third",
                              TRUE ~ rotation))

Output:

# Groups:   forest [4]
  forest season    rotation
  <chr>  <chr>     <chr>   
1 bhd    2015-2016 First   
2 bhd    2016-2017 Second  
3 bhd    2017-2018 Third   
4 flh    2018-2019 First   
5 hlc    2016-2017 First   
6 hlc    2017-2018 Second  
7 hlc    2019-2020 Third   
8 llo    2017-2018 First   
9 llo    2019-2020 Second  

Upvotes: 1

ThomasIsCoding
ThomasIsCoding

Reputation: 101034

You can try the code below

example %>% 
  group_by(forest) %>% 
  mutate(rotation = rank(season))

which gives

  forest season    rotation
  <chr>  <chr>        <dbl>
1 bhd    2017-2018        3
2 bhd    2016-2017        2
3 bhd    2015-2016        1
4 flh    2018-2019        1
5 hlc    2019-2020        3
6 hlc    2016-2017        1
7 hlc    2017-2018        2
8 llo    2019-2020        2
9 llo    2017-2018        1

Upvotes: 0

Related Questions