Nick Knauer Nick Knauer - 7 days ago 5
R Question

Reshaping a Dataframe

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!

Answer

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

library(tidyverse)

df2 <- df1 %>%
 gather(variable, value, -Family)