Home > other >  How to transform two-timepoint wide data to long format by including all time points between
How to transform two-timepoint wide data to long format by including all time points between

Time:10-24

How to transform wide data to long format by including all time points by a step length of 1?

Illustration of what I need

enter image description here

Simulated data

library(tidyverse)


df = tibble(
  id = c("a", "b", "c", "d", "e", "f"),
  time1 = c(0,1,2,3,4,5),
  time2 = c(3,2,6,7,5,9))

My own solution that gave an error

df %>% 
  mutate(
  timepoint = str_c(seq(time1, time2, 1), ",", collapse ="")) %>%   
  separate_rows(timepoint, sep = ",")

enter image description here

CodePudding user response:

You have to add rowwise:

df %>% 
  rowwise() %>% 
  mutate(timepoint = str_c(seq(time1, time2), collapse = ",")) %>%   
  separate_rows(timepoint, sep = ",", convert = TRUE)

Other solutions, in base R:

timepoint <- with(df, mapply(`:`, time1, time2))
data.frame(id = rep(df$id, lengths(timepoint)),
           timepoint = unlist(timepoint))

In tidyverse, with map2 seq (also works with :):

library(tidyverse)
df %>% 
  transmute(id, timepoint = map2(time1, time2, seq)) %>% 
  unnest(timepoint)

output

   id timepoint
1   a         0
2   a         1
3   a         2
4   a         3
5   b         1
6   b         2
7   c         2
8   c         3
9   c         4
10  c         5
11  c         6
12  d         3
13  d         4
14  d         5
15  d         6
16  d         7
17  e         4
18  e         5
19  f         5
20  f         6
21  f         7
22  f         8
23  f         9
  • Related