0

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      

1 Answers1

1

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
akrun
  • 874,273
  • 37
  • 540
  • 662