fhng fhng - 7 months ago 77
R Question

How to reshape wide continuous data into long categorical data?

My data are in the following wide format, in rows according to

SUBJECT_ID
, with a total of observations of variables
X
and
Y
and then various columns of metadata e.g.
SUBJECT_BIRTHYEAR
,
SUBJECT_HOMETOWN
:

variableX variableY SUBJECT_ID SUBJECT_BIRTHYEAR SUBJECT_HOMETOWN
2 1 A 1950 Townsville
1 2 B 1951 Villestown


I would like to transfom these into the following long format, where for each observation of variable
X
and
Y
for each
SUBJECT_ID
:

VARIABLE SUBJECT_ID SUBJECT_BIRTHYEAR SUBJECT_HOMETOWN
X A 1950 Townsville
X A 1950 Townsville
Y A 1950 Townsville
X B 1951 Villestown
Y B 1951 Villestown
Y B 1951 Villestown


Specific to my question is how to transform n observations of a continuous variable into n rows of categorical data.

Answer Source

Try the following

Data

df <- read.table(text="variableX    variableY    SUBJECT_ID     SUBJECT_BIRTHYEAR     SUBJECT_HOMETOWN
2            1            A              1950                  Townsville
1            2            B              1951                  Villestown", header=TRUE)

Solution

library(tidyverse)
result <- df %>%
        nest(variableX, variableY, .key="VARIABLE") %>%
        mutate(VARIABLE = map(VARIABLE, function(i) {
                                    vec <- unlist(i)
                                    rep(gsub("variable", "", names(vec)), times=vec)
                                })) %>%
        unnest()

# A tibble: 6 x 4
  # SUBJECT_ID SUBJECT_BIRTHYEAR SUBJECT_HOMETOWN VARIABLE
      # <fctr>             <int>           <fctr>    <chr>
# 1          A              1950       Townsville        X
# 2          A              1950       Townsville        X
# 3          A              1950       Townsville        Y
# 4          B              1951       Villestown        X
# 5          B              1951       Villestown        Y
# 6          B              1951       Villestown        Y
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download