0

I need to reshape a wide formate data into long fromat, for example, to reshape this data

dw <- read.table(header=T, text='
 sbj gender  age  avg.1 sd.1 avg.2  sd.2  
   A    1     22   10    6     50     10
   B    1     23   12    5     70     11
   C    2     21   20    7     20     8 
   D    2     20   22    8     22     9 
')

into

##      sbj gender age  var avg sd
## A.1   A  1      22   1   10  6
## B.1   B  1      23   1   12  5
## C.1   C  2      21   1   20  7
## D.1   D  2      20   1   22  8
## A.2   A  1      22   2   50 10
## B.2   B  1      23   2   70 11
## C.2   C  2      21   2   20  8
## D.2   D  2      20   2   22  9

There is a similar question, see here. However, when I input the code:

lg <- reshape(dw, 
    idvar = c("sbj", "gender", "age"), 
    varying = list(4:7), 
    v.names = c("avg", "sd"), 
    timevar = "var", 
    direction = "long")

It output the wrong result. I was quite confused with the document of the reshpe function in R, is there something wrong with my code?

user257122
  • 31
  • 4

1 Answers1

0

You can do:

library(tidyverse)
dw %>%
  pivot_longer(cols          = -c(sbj, gender, age),
               names_pattern = '(.*).(1|2)',
               names_to      = c('.value', 'var'))

# A tibble: 8 x 6
  sbj   gender   age var     avg    sd
  <chr>  <int> <int> <chr> <int> <int>
1 A          1    22 1        10     6
2 A          1    22 2        50    10
3 B          1    23 1        12     5
4 B          1    23 2        70    11
5 C          2    21 1        20     7
6 C          2    21 2        20     8
7 D          2    20 1        22     8
8 D          2    20 2        22     9
deschen
  • 10,012
  • 3
  • 27
  • 50