Terry - 1 month ago 5

R Question

`species <- c("frog1","frog1","frog1","frog1","frog1","frog1","frog1","frog1"`

,"frog1","frog1","frog2","frog2","frog2","frog2","frog2",

"frog2","frog2","frog2","frog2","frog2")

month <- c(1,12,5,8,10,3,5,7,9,4,2,4,6,7,6,3,8,9,11,1)

number <- c(3,4,5,1,2,3,4,7,6,7,3,5,6,7,8,9,9,5,3,1)

a<- data.frame(species,month,number)

my data frame means I caught two kinds of frogs,frog1 and frog2 with different numbers in different months.

I would like to convert months into 4 seasons. The first season is month 1, month 12, month 2, second is 4,3,5 , third is 7,6,8 ,and forth is 10,9,11. there is order in theses 4 seasons,namely, in the first season I would like to choose month 1 first, month 12 secondly, month 2 finally,in the same way, in the second season I would choose month 4 first, month 3 secondly, month 5 eventually, and so on.For example, in the frog 1 , there are 2 months 1 and 12, I would like to pick up the month 1 instead of month 12 for the first season.

I would like to ask how do I create a column that can choose the most important month in turn for 4 seasons in two kinds of frogs.For instance,in the frog 1 , there are 2 months 1 and 12, I would like to pick up the month 1 instead of month 12 for the first season.

My expected output is :

`species <- c("frog1","frog1","frog1","frog1","frog1","frog1","frog1","frog1"`

,"frog1","frog1","frog2","frog2","frog2","frog2","frog2",

"frog2","frog2","frog2","frog2","frog2")

month <- c(1,12,5,8,10,3,5,7,9,4,2,4,6,7,6,3,8,9,11,1)

number <- c(3,4,5,1,2,3,4,7,6,7,3,5,6,7,8,9,9,5,3,1)

choosemonth <- c("season1","","","","season4","","","season3","","season2",

"","season2","","season3","","","","season4","","season1")

b<- data.frame(species,month,number,choosemonth)

Answer

I'm guessing a little at your final desired result, but here's how to create the season and the importance, and I'm solving for the most important month for each species

Here's a way with dplyr:

```
library(dplyr)
a %>%
# Season is basically just one-off quarters
mutate(season = trunc((month + 1)%%12 / 3)) %>%
# for each month the value mod 3 goes in order 2,3,1
mutate(importance = c(2,3,1)[month %% 3 + 1]) %>%
group_by(season, species) %>%
# keep only those with the max importance
filter(importance == max(importance))
```

EDIT: It looks like you just want to flag the value with the most importance, so here's how to do that,

```
a %>%
# Season is basically just one-off quarters
mutate(season = trunc((month + 1)%%12 / 3),
# for each month the value mod 3 goes in order 2,3,1
importance = c(2,3,1)[month %% 3 + 1]) %>%
mutate(choosemonth = ifelse(importance == 3, paste0('season',season + 1),''))
```

EDIT 2: edited one more time, was dividing into 3 seasons rather than 4

Source (Stackoverflow)

Comments