-2

I would like to reshape a dataframe that looks like this:

x   y   z   Date
x1  y1  z1  1
x2  y2  z2  2
x3  y3  z3  3

into something like this:

var  val  Date
x    x1   1
x    x2   2
x    x3   3
y    y1   1
y    y2   2
y    y3   3
z    z1   1
z    z2   2
z    z3   3

I have tried this, but I lose the date variable this way:

cols1<-colnames(y[-ncol(y)]) ## to drop the Date
df_new   <- stack(df, select=c(cols1))

Is there a simple way to do this? I searched through the forum (which has a ton of reshaping questions obviously) but I could not find one that tried to do what I need to do.

This forum question for instance looks into a different problem. The original dataframe is a in different format, all the dates are individual columns. My date is one column only: Reshaping data.frame from wide to long format

Niccola Tartaglia
  • 1,537
  • 2
  • 26
  • 40
  • Where does `z1-z3` come from? Could you double check your example? – CPak Feb 05 '18 at 20:02
  • Sorry, that was a mistake, fixed it. Thank you. – Niccola Tartaglia Feb 05 '18 at 20:05
  • 2
    You should look better at the forum page you linked to and try the different solutions. `melt(df, id = 'Date')` for example gives the output you need ... – h3rm4n Feb 05 '18 at 20:11
  • You are right, I totally missed that. My apologies. Thank you though. 'melt' worked perfectly!!! – Niccola Tartaglia Feb 05 '18 at 20:14
  • Didn't you ask this same question a little while ago? – Rich Scriven Feb 05 '18 at 20:30
  • Yes I did, but it was marked as duplicate with the suggestion to ask the question again with an explanation why my question is not a duplicate. So reposted explaining why it was not a duplicate. However, I did not realize that the question was indeed a duplicate, as h3rm4n pointed out. I should have read that more carefully. – Niccola Tartaglia Feb 05 '18 at 20:34

1 Answers1

0
df <- read.table(text="x   y   z   Date
x1  y1  z1  1
x2  y2  z2  2
x3  y3  z3  3", header=TRUE, stringsAsFactors=FALSE)

library(tidyverse)
df %>%
  dplyr::group_by(Date) %>%
  tidyr::gather(var, val, x:z) %>%
  dplyr::ungroup()
CPak
  • 13,260
  • 3
  • 30
  • 48