0

The head of my data frame looks like so

Country        code   Year Population
  <chr>          <chr> <dbl>      <dbl>
 1 Afghanistan    AFG   1960     8996351
 2 Afghanistan    AFG   2016    34656032
 3 Albania        ALB   1960     1608800
 4 Albania        ALB   2016     2876101
 5 Algeria        DZA   1960    11124888
 6 Algeria        DZA   2016    40606052
 7 American Samoa ASM   1960       20013
 8 American Samoa ASM   2016       55599
 9 Andorra        AND   1960       13411
10 Andorra        AND   2016       77281

Notice how there are the years 2016 and 1960. I am trying to separate the years, so that 2016 and 1960 are their own columns. For example, I want my

I am trying to get all of the rows that have 2016 has its own column and 1960 has its own column. Also, population will have another column as well. I want to keep the code and Country columns. As an example, I would like the first row of the dataframe to look something like

Country    Code Year_1 Population_1 Year_2 Population_2
Afghanistan AFG 1960     8996351     2016    34656032

How would I go about doing this?

LoveMYMAth
  • 25
  • 5
  • A `tidyverse` option: `library(tidyverse); df %>% group_by(Country) %>% mutate(n = 1:n()) %>% ungroup() %>% pivot_longer(c(Year, Population)) %>% unite(name, name, n) %>% pivot_wider()`. I'm curious: Why reshape the data from a tidy (long) format into a messy (wide-ish) format? I would advise leaving the data as-is. – Maurits Evers Apr 04 '22 at 00:58

0 Answers0