Is there a clean way to compose sequences into there subsequences in the tidyverse?

Viewed 42

I have the following simple dataframe. I would like to find a clean tidyverse solution to decompose each sequence by row into its subsequences. I think it will be very clear what I mean when you see the examples. This is the starting code.

data.frame(acct=c(100467,100783,101233),
x1=c(4,2,4),
x2=c(3,3,4),
x3=c(2,4,4))

It produces the following output: enter image description here

I would like to modify it so that it produces basically the output of the following code:

data.frame(acct=c(100467,100467,100467,100783,100783,100783),
x1=c(4,4,4,2,2,2),
x2=c(3,3,NA,3,3,NA),
x3=c(2,NA,NA,4,NA,NA))

Which gives me the following console output:

enter image description here

What is the cleanest simplest way to accomplish this in the tidyverse? The data frame contains many more sequences to be decomposed.

1 Answers

This is not a clean way to do it, but it works:

df %>% 
  group_by(acct) %>% 
  group_map(~ accumulate(.x, c)) %>% 
  lapply(., function(x) plyr::ldply(x, rbind)) %>% 
  bind_rows() %>% 
  mutate(.id = rep(df$acct, each=3)) %>% 
  rename(acct = .id) %>% rename_with(~ paste0("x", .x), -acct)

    acct x1 x2 x3
1 100467  4 NA NA
2 100467  4  3 NA
3 100467  4  3  2
4 100783  2 NA NA
5 100783  2  3 NA
6 100783  2  3  4
7 101233  4 NA NA
8 101233  4  4 NA
9 101233  4  4  4
Related