Convert data from multivariate (wide) to univariate (stacked/tall/long) form

Average: 5 (1 vote)

Our data in multivariate (wide) format:

my_data<- data.frame(
    id=c(1:50),
    depression1=rnorm(50),
    anxiety1=rnorm(50),
    depression2=rnorm(50),
    anxiety2=rnorm(50),
    depression3=rnorm(50),
    anxiety3=rnorm(50)
)
my_data

Read more after the jump.

Now, using a function in the multilevel package:

library(multilevel)
my_data_univ <-  make.univ( data.frame(my_data$id),
    data.frame(
         my_data$anxiety1,
         my_data$anxiety2,
         my_data$anxiety3
    )
)
names(my_data_univ) <- c('id', 'time', 'anxiety')
my_data_univ

Alternatively, you can use my frame_by_name function and do:

library(multilevel)
anxiety <- frame_by_name(my_data, "anxiety")
my_data_univ <- make.univ(data.frame(my_data$id), anxiety)
names(my_data_univ) <- c('id', 'time', 'anxiety')
my_data_univ

To get both anxiety and depression in there, just do the following in addition to the code above:

depression <- frame_by_name(my_data, "depression")
d <- make.univ(data.frame(my_data$id), depression)
my_data_univ$depression <- d[[3]]

Note the double brackets, selecting the data in the 3rd column of data frame d and calling it my_data_univ$depression.