Gathering multiple columns!

Hi there! I have something like this:

example <- data.frame(country=c("Argentina","Uruguay"),
date1=c("14-feb","15-feb"),
value1=c(12,15),
date2=c("16-feb","17-feb"),
value2=c(10,15))

But i would like to have something like this:

result <- data.frame(country=c("Argentina","Uruguay","Argentina","Uruguay"),date=c("14-feb","15-feb","16-feb","17-feb"),value=c(12,15,10,15))

I have around 300 dates and numbers that need to be matched and gathered as rows, since they are samples and not variables. I usually use somthing like this:

result <- bind_rows(
example %>% select(country,date=date1,value=value1),
`example %>% select(country,date=date2,value=value2),
example %>% select(country,date=date3,value=value3),

But this time i have so many of them that i was wondering if there is any way to do this with a function. I tryied to do it but couldnt make it, I am not really good with non mathematical functions.

What would you recommend me to do?

Thank you!

I suggest you use the pivot_longer function from tidyr. I did not drop the Seq column from my result but that can be easily done if you prefer not to have it.

library(tidyr)
example <- data.frame(country=c("Argentina","Uruguay"),
                      date1=c("14-feb","15-feb"),
                      value1=c(12,15),
                      date2=c("16-feb","17-feb"),
                      value2=c(10,15))

result <- data.frame(country=c("Argentina","Uruguay","Argentina","Uruguay"),date=c("14-feb","15-feb","16-feb","17-feb"),value=c(12,15,10,15))

Myresult <- pivot_longer(example, cols = -country, 
                         names_to = c(".value", "Seq"), 
                         names_pattern = "(date|value)(\\d+)")
Myresult
#> # A tibble: 4 x 4
#>   country   Seq   date   value
#>   <fct>     <chr> <fct>  <dbl>
#> 1 Argentina 1     14-feb    12
#> 2 Argentina 2     16-feb    10
#> 3 Uruguay   1     15-feb    15
#> 4 Uruguay   2     17-feb    15
result
#>     country   date value
#> 1 Argentina 14-feb    12
#> 2   Uruguay 15-feb    15
#> 3 Argentina 16-feb    10
#> 4   Uruguay 17-feb    15

Created on 2020-06-21 by the reprex package (v0.3.0)

1 Like

Thank you, FJCC. I tried to do it with pivot_table but i did not know "names_pattern" command.

You solved my problem!

Thank you so much!!

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