reshaping the data from wide to long [duplicate]

爱⌒轻易说出口 提交于 2020-02-06 07:55:50

问题


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

回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/59847219/reshaping-the-data-from-wide-to-long

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!