0

I have a data like that :

structure(list(Event = c(2015L, 2017L, 2015L, 2018L, 2016L, 2017L, 
2015L, 2015L, 2015L)), class = "data.frame", row.names = c(NA, 
-9L))

I want to make each year (value) separate and then make those columns binominal like this.

structure(list(X2015 = c(1L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 1L), 
    X2016 = c(0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L), X2017 = c(0L, 
    1L, 0L, 0L, 0L, 1L, 0L, 0L, 0L), X2018 = c(0L, 0L, 0L, 1L, 
    0L, 0L, 0L, 0L, 0L)), class = "data.frame", row.names = c(NA, 
-9L))

So it means making columns for each year.

Ali Roghani
  • 495
  • 2
  • 7
  • 4
    You can use `model.matrix(~ factor(Event) -1, df1)` or `library(dummies);dummy(df1$Event)` – akrun Mar 24 '21 at 22:09
  • 2
    If you want a tidyverse approach, you might try `df %>% mutate(ID = 1:n(), dummy = 1) %>% pivot_wider(names_from = Event, values_from = dummy, values_fill = 0, names_glue = "X{Event}") %>% select(-ID)`. – Ian Campbell Mar 24 '21 at 22:48

0 Answers0