Home > Blockchain >  r wide to long to wide
r wide to long to wide

Time:07-26

This is a version of my dataset

ID     Name    n    Mean_SD           q2   q1_q3       Range
1      A       1477 3.42(15.12)       0.8  0.4,1.9     0     - 343.7
1      B       1475 127.114 (668.781) 0.8  3.5,29.3    0.071 - 16013.2   
2      A       445 3.35(20.41)       0.5  0.3,1.25     0.1 - 343.7
2      B       446 113.142(817.681 ) 1.7  0.775,6.225  0.1 - 9518

How do I transform this to a long-wide format like this

Name    Summary      1                   2
A       n            1477                445
        Mean_SD      3.42(15.12)         3.35(20.41) 
        q2           0.8                 0.5
        q1_q3        0.4,1.9             0.3,1.25
        Range        0 - 343.7           0.1 - 343.7
B       n            1475                446
        Mean_SD      127.114 (668.781)   113.142(817.681 ) 
        q2           0.8                 1.7
        q1_q3        3.5,29.3            0.775,6.225
        Range        0.071 - 16013.2     0.1 - 9518

Please note the Id is transformed to Wide from Long ,

n Mean_SD q2 q1_q3 Range are transformed to long from wide.

Any suggestions much appreciated. Thanks in advance.

CodePudding user response:

Use tidyr::pivot_longer and then tidyr::pivot_wider. Note that you'll have to make sure all columns are the same class to do this.

df <- structure(list(ID = c(1, 1, 2, 2), Name = c("A", "B", "A", "B"
), n = c("1477", "1475", "445", "446"), Mean_SD = c("3.42(15.12)", 
"127.114(668.781)", "3.35(20.41)", "113.142(817.681)"), q2 = c("0.8", 
"0.8", "0.5", "1.7"), q1_q3 = c("0.4,1.9", "3.5,29.3", "0.3,1.25", 
"0.775,6.225"), Range = c("0-343.7", "0.071-16013.2", "0.1-343.7", 
"0.1-9518")), row.names = c(NA, -4L), class = c("tbl_df", "tbl", 
"data.frame"))

library(dplyr)
library(tidyr)
df %>% 
  pivot_longer(c(n, Mean_SD, q2, q1_q3, Range), names_to = 'Summary') %>%
  pivot_wider(names_from = ID)
# A tibble: 10 × 4
   Name  Summary `1`              `2`         
   <chr> <chr>   <chr>            <chr>       
 1 A     n       1477             445         
 2 A     Mean_SD 3.42(15.12)      3.35(20.41) 
 3 A     q2      0.8              0.5         
 4 A     q1_q3   0.4,1.9          0.3,1.25    
 5 A     Range   0-343.7          0.1-343.7   
 6 B     n       1475             446         
 7 B     Mean_SD 127.114(668.781) 113.142(817…
 8 B     q2      0.8              1.7         
 9 B     q1_q3   3.5,29.3         0.775,6.225 
10 B     Range   0.071-16013.2    0.1-9518 

You can read more about the pivoting functions enter image description here

  • Related