1

I have the test data as follows

> date <- c('11:00', '12:00', '13:00', '11:00', '13:00', '13:00', '15:00')
> zone <- c('a', 'a', 'a', 'b', 'b', 'c', 'c')
> val <- c(1,2,3,4,5,6,7)
> test.data <- data.frame(date, zone, val)
> test.data
   date zone val
1 11:00    a   1
2 12:00    a   2
3 13:00    a   3
4 11:00    b   4
5 13:00    b   5
6 13:00    c   6
7 15:00    c   7

I need the result to be first grouped by date. And then for each unique zone a new column be added. The value of that column is picked from the column val, and if missing it's 0.

Desired Result:

result
   date zone_a zone_b zone_c
1 11:00      1      4      0
2 12:00      2      0      0
3 13:00      3      5      6
4 15:00      0      0      7
mrtyormaa
  • 862
  • 1
  • 7
  • 17

1 Answers1

1

An option is to mutate the 'zone' column by concatenating 'zone' and then spread to 'wide'

library(tidyverse)
test.data %>%
    mutate(zone = str_c("zone_", zone)) %>% 
    spread(zone, val, fill = 0)
akrun
  • 874,273
  • 37
  • 540
  • 662