Home > database >  Loop associating each locations to each months with R
Loop associating each locations to each months with R

Time:10-22

I'am trying to build a loop in order to associate different locations and several months.

Here below a simplification of my code with only 2 locations and 3 months:

require(lubridate)

seq_monthly = function(from,length.out) {
  return(from %m % months(c(0:(length.out-1))))
}
 
location<-as.data.frame(c("Paris", "London")) # The code for the locations

firstday_dates= as.data.frame(seq_monthly(as.Date(paste0("1901-01-01")), length.out= 3)) # first day of each month

lastday_dates=as.data.frame(seq(as.Date("1901-02-01"), length=3, by="1 month") - 1) #last day of each month 

# Loop 
for (d in 1: nrow(location)) {
  for (t in firstday_dates){
    for (j in lastday_dates){
        url<-paste0(d, t , j)
          }}}

The output it gives is :

[1] "London 1901-01-01 1901-01-31"
[2] "London 1901-02-01 1901-02-28"
[3] "London 1901-03-01 1901-03-31"

However what I need is:

[1] "Paris 1901-01-01 1901-01-31"
[2] "Paris 1901-02-01 1901-02-28"
[3] "Paris 1901-03-01 1901-03-31"
[6] "London 1901-01-01 1901-01-31"
[7] "London 1901-02-01 1901-02-28"
[8] "London 1901-03-01 1901-03-31"

Thank you very much for your help, Kind regards,

CodePudding user response:

Here is a base R option

sort(apply(
    expand.grid(location[, 1], paste(firstday_dates[, 1], lastday_dates[, 1])),
    1,
    paste, collapse = " "))
#[1] "London 1901-01-01 1901-01-31" "London 1901-02-01 1901-02-28" "London 1901-03-01 1901-03-31"
#[4] "Paris 1901-01-01 1901-01-31"  "Paris 1901-02-01 1901-02-28"  "Paris 1901-03-01 1901-03-31" 

Explanation: apply(..., 1, paste, collapse = " ") is the for loop in disguise, concatenating the location with the dates. expand.grid creates all combinations between location and the concatenated dates.

PS. I don't get the point of the as.data.frame calls in your sample data, as they turn a vector into a single-column data.frame and seem unnecessary.

  •  Tags:  
  • r
  • Related