0

Here is the dummy code.

x = data.frame(
  control_type = c("case","control","control"),
  gender = c("M","F","M"),
  short  = c(1,2,3),
  medium = c(5,7,4),
  long = c(9,12,10)
)

I want to get this data frame to look like the image below, but I cannot seem to figure out how to do it. In other words, convert the top part of the image to the bottom. Possibly using melt in some way? I am not sure.

https://i.stack.imgur.com/Cyfl0.png

Greg
  • 41
  • 1
  • 5
  • Does the image looks like two separate data frames. Is that the intended result? – GcL Jan 15 '20 at 20:54
  • The answer to the _related_ answer is out of date. The melt/reshape was superseded by gather/spread and that is in the process of being replaced with pivot_longer/pivot_wider. – GcL Jan 15 '20 at 21:00
  • @GcL The linked dupe target post is the post that should be referred to for wide/long reshaping. It is kept up-to-date with the newer `tidyr` options. – Maurits Evers Jan 15 '20 at 21:03
  • @MauritsEvers it's at least one generation out of date as pivot_longer is the most recent. – GcL Jan 15 '20 at 21:04
  • @GcL `spread` and `gather` are still valid. They are retired not deprecated, and `tidyr` will continue to include `spread`/`gather`. The dupe target **does include** the newer `pivot_wider`/`pivot_longer` options! – Maurits Evers Jan 15 '20 at 21:07

1 Answers1

1

We can use pivot_longer and remove the 'value' column

library(tidyr)
library(dplyr)
x %>% 
  pivot_longer(cols = short:long, names_to = c('Length')) %>% 
  dplyr::select(-value)
GcL
  • 501
  • 6
  • 16
akrun
  • 874,273
  • 37
  • 540
  • 662