0

The current data looks like this: Please run the code below

df1<- data.frame(Names= c(c(rep("Lincon",12), rep("Joe",12),rep("Megi",12))),
                 Year= c(rep(c(rep(2002,4), rep(2003,4), rep(2004,4)),3)),
                 Values= c(c(c(600, 400,210, 41),c(450, 349, 250, 42), c(200, 300,150, 43), 
                         c(500, 436, 200, 52), c(820,480,400, 53), c(500, 210, 279,54),
                         c(701, 340, 112,45), c(195, 480, 120,46),c(550, 452, 111,47))),
                 Variables= rep(c("savings","food", "transport","age"),9))

however, I would like it to look like this with the corresponding values under the variables. like this:

Names Year   savings   food   transport  age

1 Lincon 2002
2 Lincon 2002
3 Lincon 2002
4 Lincon 2002
5 Lincon 2003
6 Lincon 2003
7 Lincon 2003
8 Lincon 2003
9 Lincon 2004
10 Lincon 2004
11 Lincon 2004
12 Lincon 2004
13 Joe 2002
14 Joe 2002
15 Joe 2002
16 Joe 2002
17 Joe 2003
18 Joe 2003
19 Joe 2003
20 Joe 2003

Emmanuel
  • 19
  • 1
  • 2
  • Although I provided the answer, please see that this was already asked a zillion times in SO. THis type of operation is called a pivoting operation. – GuedesBF Jul 04 '23 at 23:26

1 Answers1

0

use pivot_wider:

library(tidyr)

df1 |> 
    pivot_wider(names_from = Variables,
                values_from = Values)


# A tibble: 9 × 6
  Names   Year savings  food transport   age
  <chr>  <dbl>   <dbl> <dbl>     <dbl> <dbl>
1 Lincon  2002     600   400       210    41
2 Lincon  2003     450   349       250    42
3 Lincon  2004     200   300       150    43
4 Joe     2002     500   436       200    52
5 Joe     2003     820   480       400    53
6 Joe     2004     500   210       279    54
7 Megi    2002     701   340       112    45
8 Megi    2003     195   480       120    46
9 Megi    2004     550   452       111    47

GuedesBF
  • 8,409
  • 5
  • 19
  • 37