Search code examples
rreshape

reshaping of dataframe in r


I want to reshape a dataframe in R and I know, that the reshape function or melt should do the trick, but I cant figure out how to write the code correctly

I have a dataframe like this:

  X       date tim eric
1 a 2022-02-02   1    2
2 b 2022-02-02   3    4
3 a 2022-03-03   5    6
4 b 2022-03-03   7    8
a <- data.frame(X = rep(c("a","b"), 2),
                date = c(rep("2022-02-02",2), rep("2022-03-03",2)),
                tim = c(1,3,5,7),
                eric = c(2,4,6,8)
                )

and i want to have the shape like this:

     x       date a b
1  tim 2022-02-02 1 3
2 eric 2022-03-03 2 4
3  tim 2022-02-02 5 7
4 eric 2022-03-03 6 8

b <-data.frame(x = rep(c("tim", "eric"),2),
date = rep(c("2022-02-02","2022-03-03"),2),
a = c(1,2,5,6),
b= c(3,4,7,8)
)

could you help me with the syntax of the functions?

I tried:

reshape(a,
varying = c("tim","eric"),
v.names = c("a", "b"),
direction = "long"
)
    X       date time a b id
1.1 a 2022-02-02    1 1 2  1
2.1 b 2022-02-02    1 3 4  2
3.1 a 2022-03-03    1 5 6  3
4.1 b 2022-03-03    1 7 8  4

which is not doing anything good but adding useless rows.

Thank you for your help in advance!


Solution

  • Consider reshaping twice in long format and then wide format:

    new_df <- reshape(
      a,
      idvar = c("X", "date"),
      varying = c("tim", "eric"),
      times = c("tim", "eric"),
      v.names = "value",
      timevar = "name",
      direction = "long",
      new.row.names = 1:1E5
    ) |> reshape(
      idvar = c("name", "date"),
      v.names = "value",
      timevar = "X",
      direction = "wide"
    ) 
    
    colnames(new_df) <- gsub(
      "value\\.", "", colnames(new_df)
    )
    
    new_df
    #         date name a b
    # 1 2022-02-02  tim 1 3
    # 3 2022-03-03  tim 5 7
    # 5 2022-02-02 eric 2 4
    # 7 2022-03-03 eric 6 8