How do I reshape/transform (cartesian to indexed) CSV data file

Hello everyone, bit confused.

I have dataset as follow in csv format. Each country row contains the recovered patients data from Date1, Date2,...DateN. Each file contains the single month data of Covid19 Recovered patients.

Country        Date1 Date2 Date3 ... DateN`
Afghanistan      0     1     0         ...
Algeria          0     1     0         ...
Andorra          0     1     0         ...

How do I can transform the above mention format csv data into following. Does not have any experience before with r language, data preparation and wrangling.

Country        Date   RecvrdPatnts
Afghanistan    Date1      0 
Afghanistan    Date2      1 
Afghanistan    Date3      0 
Andorra        Date4      0  
Andorra        Date5      1
... 
... 
Country N      DateN     RecoveredPatients

Any suggestions tip or point me some where from should I have to start for transforming data.

This is easily achieved using the pivot_longer function. Example on toy data similar to your current data below.

library(tidyverse)

patients <- tibble(
  country = c("Afghanistan", "Algeria", "Andorra"),
  date1 = c(0,0,0),
  date2 = c(1,1,1),
  date3 = c(0,0,0),
  date_n = c(1,1,1)
)

pivot_longer(patients, -country, names_to = "date", values_to = "recovered_patients")
#> # A tibble: 12 × 3
#>    country     date   recovered_patients
#>    <chr>       <chr>               <dbl>
#>  1 Afghanistan date1                   0
#>  2 Afghanistan date2                   1
#>  3 Afghanistan date3                   0
#>  4 Afghanistan date_n                  1
#>  5 Algeria     date1                   0
#>  6 Algeria     date2                   1
#>  7 Algeria     date3                   0
#>  8 Algeria     date_n                  1
#>  9 Andorra     date1                   0
#> 10 Andorra     date2                   1
#> 11 Andorra     date3                   0
#> 12 Andorra     date_n                  1

Created on 2021-10-25 by the reprex package (v2.0.1)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.