1

I have a dataset, df:

Action                        Date

Begin                         3/16/2020 12:35:47 PM
End                           3/16/2020 12:35:49 PM
Begin                         3/16/2020 01:35:47 PM
End                           3/16/2020 01:35:49 PM

Desired outcome:

Begin                          End

3/16/2020 12:35:47 PM           3/16/2020 12:35:49 PM
3/16/2020 01:35:47 PM           3/16/2020 01:35:49 PM

dput:

 structure(list(Action = structure(c(1L, 2L, 1L, 2L), .Label =       c("Begin", 
 "End"), class = "factor"), Date = structure(c(3L, 4L, 1L, 2L),      .Label = c("3/16/2020 1:35:47 PM", 
 "3/16/2020 1:35:49 PM", "3/16/2020 12:35:47 PM", "3/16/2020     12:35:49 PM"
  ), class = "factor")), class = "data.frame", row.names = c(NA, 
 -4L))

What I have tried:

I think this is a permute type problem, but not exactly sure.
Permute(df, invertdf=FALSE)

Any suggestion is helpful.

Lynn
  • 4,292
  • 5
  • 21
  • 44

1 Answers1

1

We can pivot to 'wide' format after creating a sequence column

library(dplyr)
library(data.table)
library(tidyr)
df %>% 
    mutate(rn = rowid(Action)) %>% 
    pivot_wider(names_from = Action, values_from = Date) %>%
    select(-rn)
# A tibble: 2 x 2
#  Begin                 End                  
#  <fct>                 <fct>                
#1 3/16/2020 12:35:47 PM 3/16/2020 12:35:49 PM
#2 3/16/2020 1:35:47 PM  3/16/2020 1:35:49 PM 

Or with data.table

library(data.table)
dcast(setDT(df), rowid(Action) ~ Action, value.var = 'Date')[, Action := NULL][]
#              Begin                   End
#1: 3/16/2020 12:35:47 PM 3/16/2020 12:35:49 PM
#2:  3/16/2020 1:35:47 PM  3/16/2020 1:35:49 PM

Or without using external packages with unstack (assuming equal lengths for 'Begin', 'End')

unstack(df, Date ~ Action)
#              Begin                   End
#1 3/16/2020 12:35:47 PM 3/16/2020 12:35:49 PM
#2  3/16/2020 1:35:47 PM  3/16/2020 1:35:49 PM
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Hi @akrun thank you , it is saying Error in pivot_wider(., names_from = Action, values_from = Date) : could not find function "pivot_wider" – Lynn Apr 10 '20 at 22:41
  • @TanishaHudson sorry, `library(tidyr)` forgot, updated – akrun Apr 10 '20 at 22:41
  • 1
    no sorry please, thank you it works. I will submit the checkmark in 5 minutes. – Lynn Apr 10 '20 at 22:43
  • for my knowledge, is pivot wider same as a 'permute' essentially? – Lynn Apr 10 '20 at 22:51
  • @TanishaHudson i haven't used `Permute`. Is it from an external package. I see this problem as reshaping from long to wide – akrun Apr 10 '20 at 22:53
  • 1
    ah ok! awesome. I will read up on 'pivot wider' thank you! – Lynn Apr 10 '20 at 22:53