9.6 Lab: From wide to long and back
Let’s start with wide-format…
x <- data.frame(unit = c("Peter", "Paul", "Pedro"),
trust.2006 = c(1,5,6),
trust.2007 = c(1,5,6),
Victimization.2006 = c(0,0,1),
Victimization.2007 = c(1,1,0))
unit | trust.2006 | trust.2007 | Victimization.2006 | Victimization.2007 |
---|---|---|---|---|
Peter | 1 | 1 | 0 | 1 |
Paul | 5 | 5 | 0 | 1 |
Pedro | 6 | 6 | 1 | 0 |
Convert it to long-format…
x <- x %>% pivot_longer(-unit, names_to = "variable", values_to = "value") %>%
separate(col = "variable", into = c("variable", "time"), sep = "\\.") %>%
pivot_wider(names_from = variable, values_from = value)
unit | time | trust | Victimization |
---|---|---|---|
Peter | 2006 | 1 | 0 |
Peter | 2007 | 1 | 1 |
Paul | 2006 | 5 | 0 |
Paul | 2007 | 5 | 1 |
Pedro | 2006 | 6 | 1 |
Pedro | 2007 | 6 | 0 |
Convert it back to wide-format…
x <- x %>% gather(key = variable,
value = values,
-unit,
-time) %>%
unite(variable_time, variable, time, sep = ".") %>%
spread(key = variable_time, value = values)
unit | trust.2006 | trust.2007 | Victimization.2006 | Victimization.2007 |
---|---|---|---|---|
Paul | 5 | 5 | 0 | 1 |
Pedro | 6 | 6 | 1 | 0 |
Peter | 1 | 1 | 0 | 1 |