0

How can I have the data.frame look like an output in the example below:

  created_at  negative  positive
1 2020-03-06 0.8897419 0.7564513
2 2020-03-07 0.9041667 0.7989865

Output needed:

  created_at  x         y
1 2020-03-06 negative   0.8897419 
2 2020-03-07 negative   0.9041667 
1 2020-03-06 positive   0.7564513
2 2020-03-07 positive   0.7989865

I tried the melt function, but it didn't work.

Dharman
  • 30,962
  • 25
  • 85
  • 135
WolfgangBagdanow
  • 335
  • 1
  • 3
  • 13
  • 1
    How did you tried `melt` function? This works `melt(setDT(df), id.vars = "created_at")` – Ronak Shah Apr 29 '20 at 03:37
  • Hi Ronak, I tried `df %>% group_by(created_at = cut(created_at, breaks= "1 day")) %>%melt()` First time using dplyr. Just today. Sorry sir. I looked at this forum but didn't help https://stackoverflow.com/questions/27124501/how-can-i-melt-columns-while-keeping-two-together – WolfgangBagdanow Apr 29 '20 at 03:51

1 Answers1

1

One popular approach is pivot_longer from tidyr.

library(tidyr)
data %>% 
  pivot_longer(-created_at,names_to = "x",values_to = "y")
# A tibble: 4 x 3
#  created_at x            y
#* <fct>      <chr>    <dbl>
#1 2020-03-06 negative 0.890
#2 2020-03-06 positive 0.756
#3 2020-03-07 negative 0.904
#4 2020-03-07 positive 0.799
Ian Campbell
  • 23,484
  • 14
  • 36
  • 57