-3

Issue

I have a large data frame (388 x 729) and I am trying to calculate the frequency of new daffodil bulbs (numeric column) per month (factor column) per year (numeric column) over 14 years.

I have successfully calculated the number of days that this experiment occurred per year per month from 2012 to 2024.

Now I want to add a column to show the frequency of new daffodil bulbs per year per month to the data frame previously created using the R-code (see below).

Is there a way to do both of these calculations together?

Many thanks in advance

Structure of Dataframe:

$Year : num 2012 2012 2012 2012 2012 ... $ Month : Factor w/ 18 levels "April","April ",..: 9 8 8 8 8 8 8 8 8 1 ... $ Daffodil Bulbs : num 0 3 0 3 2 1 0 0 0 0 ... 

R-Code to Calculate the Number of Days this Experiment was conducted per year per month (2012 to 2024)

Frequency_Days_Experiment<-MyDf %>% mutate(Month = factor(trimws(Month), levels = month.name, ordered = TRUE)) %>% group_by(Year, Month) %>% count() 

Dummy Code:

tibble( Month = sample(month.name, 120, replace = TRUE), Year = sample(2012:2024, 120, replace = TRUE), Number_Daffodils = sample(1:5, 120, replace = TRUE) ) 

Output from R Code

# A tibble: 96 × 3 # Groups: Year, Month [96] Year Month n <dbl> <ord> <int> 1 2012 January 1 2 2012 February 8 3 2012 April 18 4 2012 May 21 5 2012 June 27 6 2012 July 12 7 2012 October 12 8 2012 November 4 9 2012 December 3 10 2013 February 2 # ℹ 86 more rows 

Desired Output

# A tibble: 96 × 4 # Groups: Year, Month, Frequency_Daffodils [96] Year Month n n <dbl> <ord> <int> <int> 1 2012 January 1 25 2 2012 February 8 5 3 2012 April 18 13 4 2012 May 21 45 5 2012 June 27 9 6 2012 July 12 78 7 2012 October 12 12 8 2012 November 4 62 9 2012 December 3 1 10 2013 February 2 8 # ℹ 86 more rows 
3
  • 1
    Instead of %>% count(), how about %>% summarise(N = n(), Bulbs = sum(Number_Daffodils))? Commented Oct 1, 2024 at 17:43
  • There are lots of great resources on the web to help learn R and the tidyverse. I strongly recommend you look through r4ds.had.co.nz. The chapter on summarizing data should be helpful. r4ds.had.co.nz/transform.html#grouped-summaries-with-summarise Commented Oct 1, 2024 at 18:16
  • @Limey, thank you! This worked! I really did appreciate your help Commented Oct 1, 2024 at 18:25

1 Answer 1

0

Here's the solution kindly given by Limey

New_Bulbs_Frequency<-MyDf %>% mutate(Month = factor(trimws(Month), levels = month.name, ordered = TRUE)) %>% group_by(Year, Month) %>% summarise(N = n(), New_Daffodils = sum(Frequncy_Daffodils)) 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.