0

I have a question regarding changing the shape of my data frame in r.

Dataframe:

trig 

  X0        AGE    DIA5AV       BMI
1  0 -0.8347722 -19.58455 -5.064827
2  0 -0.8383630 -21.10540 -5.846960
3  0 -1.4297019 -19.93591 -5.388825
4  0 -0.7980213 -18.11637 -5.530097
5  0 -0.7980763 -19.77284 -3.798506

How can I make it so that the columns are put into a single column as rows and the row values in each of the columns are merged into one row?

Any help at all would be greatly appreciated!

Edit:

After using t to transpose I get the following:

              [,1]       [,2]       [,3]        [,4]        [,5]
X0       0.0000000   0.000000   0.000000   0.0000000   0.0000000
AGE     -0.8347722  -0.838363  -1.429702  -0.7980213  -0.7980763
DIA5AV -19.5845495 -21.105396 -19.935912 -18.1163677 -19.7728362
BMI     -5.0648265  -5.846960  -5.388825  -5.5300974  -3.7985064

How can I convert this so that it looks like the output below:


              [,1]      
X0       0.0000000   
AGE     -0.8347722  
DIA5AV -19.5845495 
BMI     -5.0648265  
X0       0.000000
AGE      -0.838363
DIA5AV  -21.105396
BMI      -5.846960 

rows continue. [,1] should contain all of the values.

Thanks!

Detr4
  • 79
  • 1
  • 8

1 Answers1

2

Using pivot_longer will produce a 2-column dataframe with the desired output:

trig %>% 
  tidyr::pivot_longer(everything())

# A tibble: 20 x 2
   name     value
   <chr>    <dbl>
 1 X0       0    
 2 AGE     -0.835
 3 DIA5AV -19.6  
 4 BMI    -25.6  
 5 X0       0    
 6 AGE     -0.838
 7 DIA5AV -21.1  
 8 BMI    -25.6  
 9 X0       0    
10 AGE     -1.43 
11 DIA5AV -19.9  
12 BMI    -25.6  
13 X0       0    
14 AGE     -0.798
15 DIA5AV -18.1  
16 BMI    -25.6  
17 X0       0    
18 AGE     -0.798
19 DIA5AV -19.8  
20 BMI    -25.6  

Since the rownames should be unique, this is probably cleaner than having a one-column dataframe with replicate rownames.

pholzm
  • 1,719
  • 4
  • 11