Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Creating a data frame with every combination of two vectors

I’m trying to create a data frame from other data, my current data includes 20 countries, 10 years from 2020-2030. I wish to now create a new df containing each country and each year separately which would look something like this;

desired df:

Albania 2021
Albania 2022
...... continued to 2030, then
Algeria 2021
Algeria 2022 and so on

data needed for this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

CountryNames
"Albania", "Algeria", "Bosnia and Herzegovina" "Croatia", "Cyprus", "Egypt, Arab Rep.", "France", "Greece", "Israel",  "Italy", "Lebanon", "Libya", "Malta", "Montenegro", "Morocco", "Slovenia", "Spain", "Syrian Arab. Rep", "Tunisia", "Turkey"
future_years
2021, 2022, 2023, 2024, 2025, 2025, 2026, 2027, 2028, 2029, 2030

>Solution :

I think you just want expand.grid:

all_df <- expand.grid(future_years = c(2021, 2022, 2023, 2024, 2025, 2025, 2026, 2027, 2028, 2029, 2030),
            CountryNames = c("Albania", "Algeria", "Bosnia and Herzegovina", 
                             "Croatia", "Cyprus", "Egypt, Arab Rep.", "France", "Greece",
                             "Israel",  "Italy", "Lebanon", "Libya", "Malta", "Montenegro",
                             "Morocco", "Slovenia", "Spain", "Syrian Arab. Rep", "Tunisia",
                             "Turkey"))[,c("CountryNames", "future_years")]

head(all_df, 10)
#>    CountryNames future_years
#> 1       Albania         2021
#> 2       Albania         2022
#> 3       Albania         2023
#> 4       Albania         2024
#> 5       Albania         2025
#> 6       Albania         2025
#> 7       Albania         2026
#> 8       Albania         2027
#> 9       Albania         2028
#> 10      Albania         2029

Created on 2022-11-13 by the reprex package (v2.0.1)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading