Widening Long Data

Hi There,

An R Studio beginner and can't seem to grasp this one..

I have data in the attached screen shot in the "Old Data" table that I would like to transform to the "New Data" using R.

Thanks!

Screen Shot 2020-08-06 at 12.08.21 PM

There is a nice primer on this (using the package tidyverse): https://rstudio.cloud/learn/primers/4.1

Although I must note that the functions gather and spread are (being) replaced by pivot_longer and pivot_wider.
I'd say the primer gives you a good introduction on how this works, and the tidyverse documentation can help you if you want to use the more updated functions:


Hope you would find this useful.

suppressPackageStartupMessages({
  library(dplyr)
  library(lubridate)
}
)
# Old Data
old_data <- tibble(
  ID = rep(101:103, times = 2),
  Date = dmy(c("1/1/20", "1/2/20", "1/3/20",
           "1/4/20", "1/5/20", "1/6/20")),
  Value = seq(from = 10, to = 60, by = 10)
)
old_data
#> # A tibble: 6 x 3
#>      ID Date       Value
#>   <int> <date>     <dbl>
#> 1   101 2020-01-01    10
#> 2   102 2020-02-01    20
#> 3   103 2020-03-01    30
#> 4   101 2020-04-01    40
#> 5   102 2020-05-01    50
#> 6   103 2020-06-01    60

# New Data
new_data1 <- old_data %>% 
  slice(1:3) %>% 
  rename(Date1 = Date, Value1 = Value)

new_data2 <- old_data %>% 
  slice(4:6) %>% 
  rename(Date2 = Date, Value2 = Value)

new_data <- inner_join(new_data1, new_data2, by = "ID")
new_data
#> # A tibble: 3 x 5
#>      ID Date1      Value1 Date2      Value2
#>   <int> <date>      <dbl> <date>      <dbl>
#> 1   101 2020-01-01     10 2020-04-01     40
#> 2   102 2020-02-01     20 2020-05-01     50
#> 3   103 2020-03-01     30 2020-06-01     60

Created on 2020-08-07 by the reprex package (v0.3.0)

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