Merging character "" with iterator i in a for loop

Hi,
I' m actually leaning R with RStudio, so I'm trying to do some function .
The problems is the following :
I'm trying to do a function which sort all the date in my dataset by month and print out the number of date for each month.
Here the function that i 'v tried :

GetNbAbsMonth <- function(varDate){
  for (i in 1:12)
  {
    month = grep(pattern = "/0"+i, x = varDate, value= TRUE)  //  get the date which contains "/01" then "/02"....  
    month[i] = count(mois) // stocking the number of each date for each month 
  }
}

But unsuccessfully.

I hope that I succed to make myself clear ( my english is shaky).
Thank for any help.

Hi,

Welcome to the RStudio community!

The code you have provided contains several errors. To start with, in R, comments are made by the # and not // . Also, trying to add an integer to a string "/0"+i is not possible like this. You have to use the paste function paste("/0"+i, sep = "").

I tried using your original function, but it's not clear what you are trying to do here and what the input / output looks like. However, I have made a small example in which I use various functions from the dplyr and lubridate package (part of the Tidyverse) to do what I think you want judging by the desctiption:

library(dplyr)
library(lubridate)

#Generate some data
set.seed(4) #Only needed for reproducibility 
myData = data.frame(
 date = as.character(Sys.Date() + sample(1:365, 10))
)
myData
#>          date
#> 1  2022-07-26
#> 2  2023-03-15
#> 3  2023-01-26
#> 4  2022-07-22
#> 5  2022-10-31
#> 6  2023-01-12
#> 7  2022-11-14
#> 8  2023-05-11
#> 9  2023-03-20
#> 10 2022-07-13


#Extact the month from each date, then sort by month, then day
myData = myData %>% 
 mutate( month = month(date), day = day(date)) %>% 
 arrange(month, day)

myData
#>          date month day
#> 1  2023-01-12     1  12
#> 2  2023-01-26     1  26
#> 3  2023-03-15     3  15
#> 4  2023-03-20     3  20
#> 5  2023-05-11     5  11
#> 6  2022-07-13     7  13
#> 7  2022-07-22     7  22
#> 8  2022-07-26     7  26
#> 9  2022-10-31    10  31
#> 10 2022-11-14    11  14

#Calculate the number of dates per month
myData %>% group_by(month) %>% summarise(n = n(), .groups = "drop")
#> # A tibble: 6 × 2
#>   month     n
#>   <dbl> <int>
#> 1     1     2
#> 2     3     2
#> 3     5     1
#> 4     7     3
#> 5    10     1
#> 6    11     1

Created on 2022-05-12 by the reprex package (v2.0.1)

Should this be close to what you like to do, I suggest you look more into the dplyr verbs to get more familiar with them.

Hope this helps,
PJ

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.