[R] Splitting data frame into columns with dplyr

Michael.Laviolette at dhhs.state.nh.us Michael.Laviolette at dhhs.state.nh.us
Thu Oct 1 14:42:24 CEST 2015


I have a data frame with a structure similar to the following. The variable
z is a grouping variable; x and y are measurement variables.

library(dplyr)
df <- data.frame(z = rep(c("A", "B")), x = 1:6, y = 7:12) %>%
  arrange(z)

  z x  y
1 A 1  7
2 A 3  9
3 A 5 11
4 B 2  8
5 B 4 10
6 B 6 12

I need to reshape into one column for each group-measurement combination as
below. Preferably using dplyr functions, how can I get to this?

  A.x   A.y   B.x   B.y
1   1     7     2     8
2   3     9     4    10
3   5    11     6    12

Thanks,
M.L.



More information about the R-help mailing list