1

I would like to transform my database from a wide format to a long format so that I can make a plot where there are the years in the x axis and the shares in the y axis. I would like to draw a line for each family because the goal is to see the gap between the two 2034 values.

This is what my dataframe currently looks like: Current Dataframe

And this is my desired output (I would call the x-axis "Year" and the y-axis "Share") Desired output

I have already tried using the "gather" option of "dplyr" using:

gather(CPS_fam.long, Year, Share, 2:5)

but I optain the years duplicated instead of the Family Name.

I cannot provide the data but any suggestion using a sample dataframe would be highly appreciated.

InesGuardans
  • 129
  • 10
  • 1
    Please share your data using `dput` instead of screenshots. Also can you show what output do you get with `tidyr::gather(CPS_fam.long, Year, Share, 2:5)` or `tidyr::gather(CPS_fam.long, Year, Share, -Fam_Name)`. Both of them should give you the desired output. – Ronak Shah Aug 24 '19 at 08:46

1 Answers1

1

I think you already got the right code but simply have to arrange the resulting data frame by Fam_Name.

Let me reproduce your problem:

library(tidyverse)

df <- tibble("Fam_Name" = c("Architecture", "Arts", "Business"), "2002" = c(0.134, 0.116, 0.399), "2018" = c(0.161, 0.089, 0.06))

df %>% gather(., key = Year, value = Shares, c("2002", "2018"))

#  Fam_Name     Year  Shares
#  <chr>        <chr>  <dbl>
#1 Architecture 2002   0.134
#2 Arts         2002   0.116
#3 Business     2002   0.399
#4 Architecture 2018   0.161
#5 Arts         2018   0.089
#6 Business     2018   0.06 

Now, with arrange as last part of the pipe:


df %>% gather(., key = Year, value = Shares, c("2002", "2018")) %>% arrange(Fam_Name)

#  Fam_Name     Year  Shares
#  <chr>        <chr>  <dbl>
#1 Architecture 2002   0.134
#2 Architecture 2018   0.161
#3 Arts         2002   0.116
#4 Arts         2018   0.089
#5 Business     2002   0.399
#6 Business     2018   0.06 

Is this what you want?

Lisardo Erman
  • 148
  • 1
  • 8