1

I have a table like this:

Type, ID, Name, Time
a, 1, abc, 2017-01-01 00:00:00
b, 1, abc, 2017-01-01 00:01:00
a, 1, abc, 2017-01-01 00:02:00
b, 1, abc, 2017-01-01 00:03:00

And I'm trying to convert to wide format like this:

ID, Name, a, b
1, abc, 2017-01-01 00:00:00, 2017-01-01 00:01:00
1, abc, 2017-01-01 00:02:00, 2017-01-01 00:03:00

I'm using the spread function from tidyr, but how do I keep the ID and name column?

ajax2000
  • 711
  • 2
  • 10
  • 23

1 Answers1

2

We can use spread after creating a sequence column by 'Type', 'ID', and 'Name' columns

library(tidyverse)
df %>%
  group_by(Type, ID, Name) %>%
  mutate(n = row_number()) %>%
  spread(Type, Time) %>%
  select(-n)
# A tibble: 2 x 4
# Groups:   ID, Name [1]
#  ID    Name  a                   b                  
#  <chr> <chr> <chr>               <chr>              
#1 1     abc   2017-01-01 00:00:00 2017-01-01 00:01:00
#2 1     abc   2017-01-01 00:02:00 2017-01-01 00:03:00

data

df <- structure(list(Type = c("a", "b", "a", "b"), ID = c("1", "1", 
"1", "1"), Name = c("abc", "abc", "abc", "abc"), Time = c("2017-01-01 00:00:00", 
 "2017-01-01 00:01:00", "2017-01-01 00:02:00", "2017-01-01 00:03:00"
)), row.names = c(NA, -4L), class = "data.frame")
akrun
  • 874,273
  • 37
  • 540
  • 662