How to pass my dataset from wide format to long cm in multiple variables in R

2

I have the following date frame:

dput(exemplo)
structure(list(id = c(1, 2, 3, 4, 5, 6, 7),
    grupo = c("A", "A", "A", "B", "B", "B", NA),
    fc_pre = c(90, 98, 77, 98, 100, 92, 89),
    fc_pos = c(70, 77, 77, 70, 79, 72, 76),
    pa_pre = c(130, 140, 160, 160, 120, 120, 150),
    pa_pos = c(120, 110, 140, 150, 130, 120, 130)),
   .Names = c("id", "grupo", "fc_pre", "fc_pos", "pa_pre", "pa_pos"), 
    class = c("tbl_df", "tbl", "data.frame"),
    row.names = c(NA, -7L))

I put it in long format using the code:

    library(reshape2)
    longo <- melt(exemplo, id=c("id", "grupo"))

My date frame has been in long format. But, R placed fc_pre to fc_pos to pa_pre and pa_pos in the same vector.

    longo
    id grupo variable value
 1   1     A   fc_pre    90
 2   2     A   fc_pre    98
 3   3     A   fc_pre    77
 4   4     B   fc_pre    98
 5   5     B   fc_pre   100
 15  1     A   pa_pre   130
 16  2     A   pa_pre   140
 17  3     A   pa_pre   160
 18  4     B   pa_pre   160
 19  5     B   pa_pre   120

I would like it to look like this:

 # A tibble: 14 x 5
       id grupo tempo     fc     pa
    <dbl> <chr> <chr>  <dbl>  <dbl>
  1     1     A   pre     90    130
  2     2     A   pre     98    140
  3     3     A   pre     77    160
  4     4     B   pre     98    160
  5     5     B   pre    100    120
  6     6     B   pre     92    120
  8     1     A   pos     70    120
  9     2     A   pos     77    110
 10     3     A   pos     77    140
 11     4     B   pos     70    150
 12     5     B   pos     79    130

Now I have one vector called time, another called fc and another called pa. Can anyone tell me how to restructure my data frame to stay like this?

    
asked by anonymous 24.08.2017 / 05:20

1 answer

2

Hello, in order to do this, it is necessary to combine the functions melt and dcast of the reshape2 package together with the sub function.

require(reshape2)
longo <- melt(df, id.vars=c("id","grupo")) # Passo as variáveis do formato wide para longo
longo$tempo <- factor(with(longo, sub(".*_","",variable))) #Crio a variável tempo
longo$variavel <- factor(with(longo, sub("_.*","",variable))) #Crio a variável em questão
longo <- longo[,-3]
longo <- dcast(longo, id + grupo + tempo ~ variavel) # Volto as variáveis que ficaram no formato "wide" para longo.

After this, the dataframe looks like this:

  id grupo tempo fc  pa
1  1     A   pos 70 120
2  1     A   pre 90 130
3  2     A   pos 77 110
4  2     A   pre 98 140
5  3     A   pos 77 140
6  3     A   pre 77 160

Note that for this code to work, it is necessary that the columns in the original dataframe (df) obey some pattern so that the sub () function is able to correctly separate the variable name from the moment it was measured. p>     

24.08.2017 / 15:35