From wide to long dataframe

Hi,
My data frame is as follows:

I would like to transpose it to long form as follows, my desired result:

obraz

I would be grateful for any help, please and thank you.

data <- structure(list(Sample = c(
  "P_1", "P_2", "P_3", "P_4", "P_1",
  "P_2", "P_3", "P_4", "P_1", "P_2", "P_3", "P_4"
), `3min` = c(
  61.34,
  62.12, 61.54, 61.85, 60.16, 61.9, 62.04, 61.57, 59.63, 61.15,
  60.12, 62.24
), `15min` = c(
  61.24, 62.06, 61.44, 61.78, 60.08,
  61.83, 61.96, 61.5, 59.57, 61.05, 60.09, 62.12
), `30min` = c(
  61.13,
  61.96, 61.37, 61.7, 60.03, 61.68, 61.85, 61.42, 61.02, 60.98,
  59.98, 62.02
), `45min` = c(
  61.07, 61.84, 61.24, 61.64, 59.96,
  61.56, 61.72, 61.36, 59.43, 60.92, 59.93, 61.92
), `60min` = c(
  60.99,
  61.82, 61.22, 61.56, 59.91, 61.52, 61.65, 61.24, 59.38, 60.87,
  59.88, 61.83
), `90min` = c(
  60.9, 61.7, 61.07, 61.44, 59.79, 61.42,
  61.54, 61.13, 59.24, 60.75, 59.74, 61.7
), `120min` = c(
  60.79,
  61.57, 60.98, 61.3, 59.7, 61.34, 61.44, 61.04, 59.13, 60.62,
  59.68, 61.6
), `180min` = c(
  60.55, 61.35, 60.76, 61.04, 59.45,
  61.17, 61.18, 60.8, 58.85, 60.31, 59.34, 61.33
), `30h` = c(
  59.06,
  59.72, 59, 60, 57.61, 59.24, 59.13, 60.59, 57.92, 58.82, 58.03,
  59.21
), Liquid = c(
  "tap_water", "tap_water", "tap_water", "tap_water",
  "Alloran", "Alloran", "Alloran", "Alloran", "Victoria", "Victoria",
  "Victoria", "Victoria"
)), row.names = c(NA, -12L), class = c(
  "tbl_df",
  "tbl", "data.frame"
))

Hi @Andrzej,

This is a good use-case for tidyr::pivot_longer():

library(tidyverse)

data %>% 
  pivot_longer(
    cols = c(contains('min'), `30h`),
    names_to = 'time_points',
    values_to = 'score'
  )

Hi @mattwarkentin,
Thank you very much,
how should I sort resulting dataframe that "sample" column will be displayed in ascending order as I have got here repeated measures recorded :
obraz

data %>% 
  pivot_longer(
    cols = c(contains('min'), `30h`),
    names_to = 'time_points',
    values_to = 'score'
  ) %>%
  arrange(time_points)

Thank you, we are getting there as time_points colum should be in ascending order as well, but at present it is not:

obraz

You may wish to look into the help documentation for ?arrange to learn how to sort in ascending and descending orders.

Thank you @mattwarkentin for your kind help, I will read about it.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.