Habert
Habert

Reputation: 347

Lubridate periods get messed up after using dplyr spread

I am using R-3.6.3, lubridate_1.7.4, dbplyr_1.4.2.

Reprex:

df_0 <- tibble(period_type  = c("a", "b", "c"), 
               period_value = c("1:1:1", "2:2:2", "4:4:4")) %>% 
        mutate(period_value = hms(period_value))

df_0
## A tibble: 3 x 2
#  period_type period_value
#  <chr>       <Period>
#1 a           1H 1M 1S
#2 b           2H 2M 2S
#3 c           4H 4M 4S

So far so good. Now using dplyr spread:

df_0 %>% spread(period_type, period_value)
## A tibble: 1 x 3
#  a        b        c
#  <Period> <Period> <Period>
#1 1H 1M 1S 1H 1M 2S 1H 1M 4S

But the result should be

## A tibble: 1 x 3
#  a        b        c
#  <Period> <Period> <Period>
#1 1H 1M 1S 2H 2M 2S 4H 4M 4S

Hours and minutes get messed up, but strangely not seconds. Is that a bug or am I doing something wrong?

Upvotes: 2

Views: 141

Answers (2)

MarkusN
MarkusN

Reputation: 3223

The problem is not the tidyr verb, as spread() isn't going away but is no longer under active development

Instead of lubridate, try function parse_hms() of package hms:

df_0 <- tibble(period_type  = c("a", "b", "c"), 
           period_value = c("1:1:1", "2:2:2", "4:4:4")) %>% 
  mutate(period_value = hms::parse_hms(period_value))

df_0 %>% spread(period_type, period_value)
# or
df_0 %>% pivot_wider(names_from=period_type, values_from=period_value)

# A tibble: 1 x 3
  a        b        c       
  <time>   <time>   <time>  
1 01:01:01 02:02:02 04:04:04

Upvotes: 2

lroha
lroha

Reputation: 34601

As Edward has commented, pivot_wider() has replaced spread(). However, it doesn't seem to handle variables of period class. So you need to convert the period values, pivot, then convert back.

library(dplyr)
library(lubridate)

df_0 %>%
  mutate(period_value = period_to_seconds(period_value)) %>%
  pivot_wider(names_from = period_type, values_from = period_value) %>%
  mutate_all(seconds_to_period)

# A tibble: 1 x 3
  a        b        c       
  <Period> <Period> <Period>
1 1H 1M 1S 2H 2M 2S 4H 4M 4S

Upvotes: 2

Related Questions