1

I have a dataframe as such:

Family <- c('A','B','C', 'D', 'E', 'F', 'G', 'H', 'I', 'J')
This_Month <- c(1000, 2000, 3000, 4000, 5000, 6000,7000,8000,9000,10000)
Last_Month <- c(11000, 12000, 13000, 14000, 15000, 16000,17000,18000,19000,20000)

df1 <- data.frame(Family, This_Month, Last_Month)

   Family    This_Month   Last_Month
1       A          1000        11000
2       B          2000        12000
3       C          3000        13000
4       D          4000        14000
5       E          5000        15000
6       F          6000        16000
7       G          7000        17000
8       H          8000        18000
9       I          9000        19000
10      J         10000        20000

How do I reshape this so that it turns into the dataframe below. I want to take the columns This_Month and Last_Month and turn them into row values with it's corresponding numbers.

      Date        Family    Revenue
This_Month             A       1000
Last_Month             A      11000
This_Month             B       2000
Last_Month             B      12000
This_Month             C       3000
Last_Month             C      13000
This_Month             D       4000
Last_Month             D      14000
This_Month             E       5000
Last_Month             E      15000
This_Month             F       6000
Last_Month             F      16000
This_Month             G       7000
Last_Month             G      17000
This_Month             H       8000
Last_Month             H      18000
This_Month             I       9000
Last_Month             I      19000
This_Month             J      10000
Last_Month             J      20000

Thanks!

A.Yazdiha
  • 1,336
  • 1
  • 14
  • 29
nak5120
  • 4,089
  • 4
  • 35
  • 94

2 Answers2

1

Just make use of the amazing tidyverse and specifically the gather() function.

library(tidyverse)

df2 <- df1 %>%
 gather(variable, value, -Family)
boshek
  • 4,100
  • 1
  • 31
  • 55
1

You can use melt from package reshape2:

> library('reshape2')
> melt(df1, id='Family', variable.name='Date')
    Family       Date value
1       A This_Month  1000
2       B This_Month  2000
3       C This_Month  3000
4       D This_Month  4000
5       E This_Month  5000
6       F This_Month  6000
7       G This_Month  7000
8       H This_Month  8000
9       I This_Month  9000
10      J This_Month 10000
11      A Last_Month 11000
12      B Last_Month 12000
13      C Last_Month 13000
14      D Last_Month 14000
15      E Last_Month 15000
16      F Last_Month 16000
17      G Last_Month 17000
18      H Last_Month 18000
19      I Last_Month 19000
20      J Last_Month 20000
user1981275
  • 13,002
  • 8
  • 72
  • 101