Search code examples
rvectormergereadability

Is there a specific function in R to merge 2 vectors


I have two vectors, one that contains a list of variables, and one that contains dates, such as

Variables_Pays <- c("PIB", "ConsommationPrivee","ConsommationPubliques",
                    "FBCF","ProductionIndustrielle","Inflation","InflationSousJacente",
                    "PrixProductionIndustrielle","CoutHoraireTravail")
Annee_Pays <- c("2000","2001")

I want to merge them to have a vector with each variable indexed by my date, that is my desired output is

> Colonnes_Pays_Principaux
 [1] "PIB_2020"                        "PIB_2021"                        "ConsommationPrivee_2020"        
 [4] "ConsommationPrivee_2021"         "ConsommationPubliques_2020"      "ConsommationPubliques_2021"     
 [7] "FBCF_2020"                       "FBCF_2021"                       "ProductionIndustrielle_2020"    
[10] "ProductionIndustrielle_2021"     "Inflation_2020"                  "Inflation_2021"                 
[13] "InflationSousJacente_2020"       "InflationSousJacente_2021"       "PrixProductionIndustrielle_2020"
[16] "PrixProductionIndustrielle_2021" "CoutHoraireTravail_2020"         "CoutHoraireTravail_2021" 

Is there a simpler / more readabl way than a double for loop as I have tried and succeeded below ?

Colonnes_Pays_Principaux <- vector()
for (Variable in (1:length(Variables_Pays))){
  for (Annee in (1:length(Annee_Pays))){
     Colonnes_Pays_Principaux=
       append(Colonnes_Pays_Principaux,
              paste(Variables_Pays[Variable],Annee_Pays[Annee],sep="_")
              )
  }
}

Solution

  • No real need to go beyond the basics here! Use paste for pasting the strings and rep to repeat either Annee_Pays och Variables_Pays to get all combinations:

    Variables_Pays <- c("PIB", "ConsommationPrivee","ConsommationPubliques",
                       "FBCF","ProductionIndustrielle","Inflation","InflationSousJacente",
                        "PrixProductionIndustrielle","CoutHoraireTravail")
    Annee_Pays <- c("2000","2001")
    
    # To get this is the same order as in your example:
    paste(rep(Variables_Pays, rep(2, length(Variables_Pays))), Annee_Pays, sep = "_")
    
    # Alternative order:
    paste(Variables_Pays, rep(Annee_Pays, rep(length(Variables_Pays), 2)), sep = "_")
    
    # Or, if order doesn't matter too much:
    paste(Variables_Pays, rep(Annee_Pays, length(Variables_Pays)), sep = "_")