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

'Stretch' a grouped data frame using dplyr

I have a grouped dataframe with multiple IDs with a date and value column.

id <- c("a", "a", "a", "b", "b", "b", "c")
date <- c("2020-01-01", "2020-01-02", "2020-01-03",
          "2020-01-01", "2020-01-02", "2020-01-03",
          "2020-01-01")
value <- rnorm(n = length(id))
df <- cbind.data.frame(id, date, value)

However, some IDs have less than 3 dates. I want to "stretch" those IDs and add an NA for the value column for the new dates. In this dataframe, the "c" ID would have two new dates added ("2020-01-02" and "2020-01-03").

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

>Solution :

Perhaps this approach would suit?

library(tidyverse)

id <- c("a", "a", "a", "b", "b", "b", "c")
date <- c("2020-01-01", "2020-01-02", "2020-01-03",
          "2020-01-01", "2020-01-02", "2020-01-03",
          "2020-01-01")
value <- rnorm(n = length(id))
df <- cbind.data.frame(id, date, value)

df %>%
  right_join(df %>% expand(id, date))
#> Joining, by = c("id", "date")
#>   id       date      value
#> 1  a 2020-01-01 -1.5371474
#> 2  a 2020-01-02  0.9001098
#> 3  a 2020-01-03  0.1523491
#> 4  b 2020-01-01  0.8194577
#> 5  b 2020-01-02  1.2005270
#> 6  b 2020-01-03  0.1158812
#> 7  c 2020-01-01 -0.8676445
#> 8  c 2020-01-02         NA
#> 9  c 2020-01-03         NA

Created on 2022-09-05 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