0

Please help me with the following matter I have a wide data frame that I need to reshape.
This is the df I have

mydf <- data.frame(date=1983:1985,January=c(5,7,8),February=c(12,18,19))  
mydf

this is the output I need

output <- data.frame(date=rep(c(1983,1984,1985),each=2),Month=rep(c("January","February"),3),Value=c(5,12,7,18,8,19))
output
Rlearner
  • 93
  • 5

2 Answers2

0

Using melt from reshape2:

reshape2::melt(mydf, id.vars = "date", measure.vars = c("January", "February"), variable.name = "Month", value.name = "Value")

 #  date    Month Value
 #1 1983  January     5
 #2 1984  January     7
 #3 1985  January     8
 #4 1983 February    12
 #5 1984 February    18
 #6 1985 February    19
sm925
  • 2,648
  • 1
  • 16
  • 28
-2

We can use pivot_longer

library(tidyr)
library(dplyr)
mydf %>%
    pivot_longer(cols = -date, names_to = 'Month', values_to = 'Value')
#  date    Month Value
#1 1983  January     5
#2 1983 February    12
#3 1984  January     7
#4 1984 February    18
#5 1985  January     8
#6 1985 February    19
akrun
  • 874,273
  • 37
  • 540
  • 662