Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Transpose only certain columns – data formating

Im trying to modify some data and have the following data now:

df <- data.frame(year = c(2010,2011,2010,2011),A = c(10,11,10,11),B = c(11,12,11,12))


  year        A         B
1 2010        10        11
2 2011        11        12
3 2010        10        11
4 2011        11        12

I want it to look like this, but do not know how to do it. Can anyone help me?

  company year   Variable
1   A      2010  10           
2   A      2011  11            
3   B      2010  11             
4   B      2011  12      

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

We can use pivot_longer

library(tidyr)
pivot_longer(df, cols = -year, 
   names_to = 'company', values_to = 'Variable')

-output

# A tibble: 8 × 3
   year company Variable
  <dbl> <chr>      <dbl>
1  2010 A             10
2  2010 B             11
3  2011 A             11
4  2011 B             12
5  2010 A             10
6  2010 B             11
7  2011 A             11
8  2011 B             12
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading