0

I know that this question is repeated here but reviewing the other questions, I did not find a solution for mine, I want to separate the columns according to cases and population something like this:

pais        anio tipo          cuenta
   <chr>      <int> <chr>          <int>
 1 Afganistán  1999 casos            745
 2 Afganistán  1999 población   19987071
 3 Afganistán  2000 casos           2666
 4 Afganistán  2000 población   20595360
 5 Brasil      1999 casos          37737
 6 Brasil      1999 población  172006362
 7 Brasil      2000 casos          80488
 8 Brasil      2000 población  174504898
 9 China       1999 casos         212258
10 China       1999 población 1272915272
11 China       2000 casos         213766
12 China       2000 población 1280428583

I want it to look like this:

 pais        anio  casos  poblacion
  <chr>      <int>  <int>      <int>
1 Afganistán  1999    745   19987071
2 Afganistán  2000   2666   20595360
3 Brasil      1999  37737  172006362
4 Brasil      2000  80488  174504898
5 China       1999 212258 1272915272
6 China       2000 213766 1280428583

try with mutate and filter but it doesn't alter the shape of the table, please and thank you

Phil
  • 7,287
  • 3
  • 36
  • 66

1 Answers1

0

Use pivot_wider from tidyr package:

> library(tidyr)
> datos %>% 
    pivot_wider(names_from  = tipo, values_from = cuenta)
# A tibble: 6 × 4
  pais        anio  casos  población
  <chr>      <int>  <int>      <int>
1 Afganistán  1999    745   19987071
2 Afganistán  2000   2666   20595360
3 Brasil      1999  37737  172006362
4 Brasil      2000  80488  174504898
5 China       1999 212258 1272915272
6 China       2000 213766 1280428583

Use this data frame to reproduce the example:

datos <- read.table(text="pais        anio tipo          cuenta
 1 Afganistán  1999 casos            745
 2 Afganistán  1999 población   19987071
 3 Afganistán  2000 casos           2666
 4 Afganistán  2000 población   20595360
 5 Brasil      1999 casos          37737
 6 Brasil      1999 población  172006362
 7 Brasil      2000 casos          80488
 8 Brasil      2000 población  174504898
 9 China       1999 casos         212258
10 China       1999 población 1272915272
11 China       2000 casos         213766
12 China       2000 población 1280428583")
Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138