reshape() function to make wide to long data

44 views Asked by At
set.seed(123)
data <- data.frame(ID = 1:10,
                   weight_hus = rnorm(10, 0, 1),
                   weight_wife = rnorm(10, 0, 1),
                   height_hus = rnorm(10, 0, 1),
                   height_wife = rnorm(10, 0, 1))

I am trying to use reshape() function

(due to some reasons, I can not use tidyverse function or other packages' function. wanna use reshape() function)

data2 <- reshape(data = data,
                 idvar = "ID",
                 seperator = "_",
                 direction = "long",
                 v.name = c("body"),
                 timevar = c("hus", wife)
               )

but it never works...

1

There are 1 answers

1
gamez hetrick On BEST ANSWER

Here is the code:

set.seed(123)
data <- data.frame(ID = 1:10,
                   weight_hus = rnorm(10, 0, 1),
                   weight_wife = rnorm(10, 0, 1),
                   height_hus = rnorm(10, 0, 1),
                   height_wife = rnorm(10, 0, 1))

data2 <- reshape(data = data,
                 idvar = "ID",
                 varying = list(c("weight_hus", "weight_wife"), c("height_hus", "height_wife")),
                 v.names = c("weight", "height"),
                 direction = "long",
                 times = c("hus", "wife"),
                 timevar = "gender"
               )

Changes made:

  1. Replaced seperator with varying to specify the variables to be reshaped.
  2. Used v.names to provide meaningful names for the reshaped variables.
  3. Changed timevar to "gender" to represent the different groups ("hus" and "wife").