Yannik Suhre
Yannik Suhre

Reputation: 734

Gather serveral columns at once in r

I am trying to gather() a data.frame, but somehow it is not doing what I want. This is my data:

df <- data.frame("id" = c(1),
                 "reco_1"= c(2),
                 "sim_1" = c(2),
                 "title_1"= c(2),
                 "reco_2" = c(3),
                 "sim_2" = c(3),
                 "title_2"= c(3))

And this is what it looks like printed:

> df
  id reco_1 sim_1 title_1 reco_2 sim_2 title_2
1  1      2     2       2      3     3       3

When I now gather() my df, it looks like this:

> df %>% gather(reco, sim, -id)
  id    reco sim
1  1  reco_1   2
2  1   sim_1   2
3  1 title_1   2
4  1  reco_2   3
5  1   sim_2   3
6  1 title_2   3

However, what I would like to have is the following structure:

  id  reco  sim  title
1  1  2     2    2
2  2  3     3    3

I would appreciate any help, since I do not even know whether gather() is even the right verb for it.

Upvotes: 0

Views: 35

Answers (1)

Ahorn
Ahorn

Reputation: 3876

We can use pivot_longer

library(dplyr)
library(tidyr)
df %>% 
  pivot_longer(-id, names_to = c(".value", "new_id"), names_sep = "_") %>% 
  select(-id)

# A tibble: 2 x 4
  new_id  reco   sim title
  <chr>  <dbl> <dbl> <dbl>
1 1          2     2     2
2 2          3     3     3

Upvotes: 3

Related Questions