Original data:
df <- structure(list(ID_client = structure(c(1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L), .Label = c("1_", "2_", "3_", "4_"), class = "factor"), Connected = c(1L, 1L, 1L, 0L, 1L, 0L, 1L, 0L), Year = c(2010L, 2010L, 2010L, 2010L, 2015L, 2015L, 2015L, 2015L)), class = "data.frame", row.names = c(NA, -8L))
Original data:
`ID_client Connected Year
1_ 1 2010
2_ 1 2010
3_ 1 2010
4_ 0 2010
1_ 1 2015
2_ 0 2015
3_ 1 2015
4_ 0 2015`
My intention is to create the following data:
`Year ID_client 1_ 2_ 3_ 4_
2010 1_ 0 1 1 0
2010 2_ 1 0 1 0
2010 3_ 1 1 0 0
2010 4_ 0 0 0 0
2015 1_ 0 0 1 0
2015 2_ 0 0 0 0
2015 3_ 1 0 0 0
2015 4_ 0 0 0 0`
In other words, a matrix that express that in, for instance, 2010 clients 1_, 2_, and 3_ were connected, while the other one was not. Importantly, I do not consider someone to be connected with herself.
I have tried the following code:
df %>%
group_by(Year, Connected) %>%
mutate(temp = rev(ID_client)) %>%
pivot_wider(names_from = ID_client,
values_from = Connected,
values_fill = list(Connected = 0)) %>%
arrange(Year, temp)
This code does not reproduce what I need. Instead, this is the result:
`Year ID_client 1_ 2_ 3_ 4_
2010 1_ 0 0 1 0
2010 2_ 0 1 0 0
2010 3_ 1 0 0 0
2010 4_ 0 0 0 0
2015 1_ 0 0 1 0
2015 2_ 0 0 0 0
2015 3_ 1 0 0 0
2015 4_ 0 0 0 0`