Search code examples
rreshape2

Converting many variables from long to wide in R


I wish to convert many variables from long to wide in R. I have clustered data with family as a cluster, and in each family individuals. For each individual several measured variables, each measured more than once. In the example below, you can see two variables x and y, each measured twice.

I know how to do this for one variable, using the reshape2 package and the dcast function, but it doesn't work for more than one.

I am attaching a picture of example data and the code that generated it.

family = c(1,1,1,2,2,2,3,3,3,1,1,1,2,2,2,3,3,3)
id = c(1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3)
time = c(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1)
x = round(runif(18,1,10))
y = round(runif(18,1,10))

D = data.frame(family, id, time, x, y)

enter image description here

The output should be a data frame with the following variables: family, id, x_1, x_2, y_1, y_2.

Edit:

You can see an example here:

enter image description here

Thank you !


Solution

  • You can create a unique identifier row for every family, id and time variable and then use pivot_wider.

    library(dplyr)
    
    D %>% 
       group_by(family, id, time) %>% 
       mutate(row = row_number()) %>% 
       tidyr::pivot_wider(names_from = time, values_from = c(x, y))