0

Here is data frame I have:

 .id     dn     mavg    up      pctB
  1    18.8    21.1    23.4    0.8 
  1    18.7    21.1    23.5    0.8 
  1    18.7    21.2    23.7    0.8 
  2    23.1    24.6    26.1    0.5 
  2    23.1    24.6    26.0    0.4 
  2    23.1    24.5    26.0    0.5 
  3    145.5   179.2   212.9   0.3 
  3    144.2   177.4   210.7   0.3 
  3    143.4   175.6   207.7   0.3 

The shape that I want to have is following:

.id  dn.1   dn.2    dn.3    mavg.1  mavg.2  mavg.3  up.1    up.2    up.3    pctB.1  pctB.2  pctB.3
 1   18.8   18.7    18.7    21.1    21.1    21.2    23.4    23.5    23.7     0.8     0.8     0.8
 2   23.1   23.1    23.1    24.6    24.6    24.5    26.1    26       26      0.5     0.4     0.5
 3   145.5  144.2   143.4   179.2   177.4   175.6   212.9   210.7   207.7    0.3     0.3     0.3

I know how to keep only one of columns from my original data frame, but I need to keep every column like right above. How can I do this?

  • 1
    https://stackoverflow.com/questions/5890584/how-to-reshape-data-from-long-to-wide-format – jogo Sep 09 '20 at 06:47

1 Answers1

0

Here is one option after creating a sequence column by '.id'

library(dplyr)
library(tidyr)
library(data.table)
df1 %>%
   mutate(rn  = rowid(.id)) %>%
   pivot_wider(names_from = rn, values_from = c(dn, mavg, up, pctB))          
# A tibble: 3 x 13
#    .id  dn_1  dn_2  dn_3 mavg_1 mavg_2 mavg_3  up_1  up_2  up_3 pctB_1 pctB_2 pctB_3
#  <int> <dbl> <dbl> <dbl>  <dbl>  <dbl>  <dbl> <dbl> <dbl> <dbl>  <dbl>  <dbl>  <dbl>
#1     1  18.8  18.7  18.7   21.1   21.1   21.2  23.4  23.5  23.7    0.8    0.8    0.8
#2     2  23.1  23.1  23.1   24.6   24.6   24.5  26.1  26    26      0.5    0.4    0.5
#3     3 146.  144.  143.   179.   177.   176.  213.  211.  208.     0.3    0.3    0.3

data

df1 <- structure(list(.id = c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L), dn = c(18.8, 
18.7, 18.7, 23.1, 23.1, 23.1, 145.5, 144.2, 143.4), mavg = c(21.1, 
21.1, 21.2, 24.6, 24.6, 24.5, 179.2, 177.4, 175.6), up = c(23.4, 
23.5, 23.7, 26.1, 26, 26, 212.9, 210.7, 207.7), pctB = c(0.8, 
0.8, 0.8, 0.5, 0.4, 0.5, 0.3, 0.3, 0.3)), class = "data.frame",
row.names = c(NA, 
-9L))
akrun
  • 874,273
  • 37
  • 540
  • 662