1

I have the dataframe below:

dput(Moment[1:15,])
structure(list(SectionCut = c("1", "1", "1", "1", "2", "2", "2", 
"2", "3", "3", "3", "3", "Left", "Left", "Left"), N_l = c("1", 
"2", "3", "4", "1", "2", "3", "4", "1", "2", "3", "4", "1", "2", 
"3"), UG = c("84", "84", "84", "84", "84", "84", "84", "84", 
"84", "84", "84", "84", "84", "84", "84"), S = c("12", "12", 
"12", "12", "12", "12", "12", "12", "12", "12", "12", "12", "12", 
"12", "12"), Sample = c("S00", "S00", "S00", "S00", "S00", "S00", 
"S00", "S00", "S00", "S00", "S00", "S00", "S00", "S00", "S00"
), DF = c(0.367164093630677, 0.540130283330855, 0.590662743113521, 
0.497030982705986, 0.000319303760901125, 0.000504925126205843, 
0.00051127115578891, 0.000395434233037301, 0.413218926236695, 
0.610726262711904, 0.685000816613652, 0.59474035159783, 0.483354599644366, 
0.645710184115934, 0.625883097885242)), row.names = c(NA, -15L
), class = c("tbl_df", "tbl", "data.frame"))

I want to separate the content of the column by pivoting the SectionCut column. I would basically want to use the opposite of pivot_longer somehow... so at the end the values in column DF will be shown under 5 different columns (the values of SectionCut = c("1", "2", "3", "left", "right")

Maral Dorri
  • 468
  • 5
  • 17

1 Answers1

1

We could use pivot_wider from tidyr after creating a sequence column with rowid

library(dplyr)
library(tidyr0
library(data.table)
Moment %>% 
     mutate(rn = rowid(SectionCut)) %>% 
     pivot_wider(names_from = SectionCut, values_from = DF)

-output

# A tibble: 4 x 9
#  N_l   UG    S     Sample    rn   `1`      `2`   `3`   Left
#  <chr> <chr> <chr> <chr>  <int> <dbl>    <dbl> <dbl>  <dbl>
#1 1     84    12    S00        1 0.367 0.000319 0.413  0.483
#2 2     84    12    S00        2 0.540 0.000505 0.611  0.646
#3 3     84    12    S00        3 0.591 0.000511 0.685  0.626
#4 4     84    12    S00        4 0.497 0.000395 0.595 NA    
akrun
  • 874,273
  • 37
  • 540
  • 662