tidyr gather: simultaneously gather and rename key?

2.1k views Asked by At

Suppose I have the following data frame:

> a <- data_frame(my_type_1_num_widgets = c(1, 2, 3), my_type_2_num_widgets = c(4, 5, 6))
> a
Source: local data frame [3 x 2]

  my_type_1_num_widgets my_type_2_num_widgets
1                     1                     4
2                     2                     5
3                     3                     6

I want to do two things:

  1. gather the "num_widgets" columns.
  2. rename the resulting keys to remove the "num_widgets" suffix.

The way I'm doing this currently, and the correct/desired output that I'm getting:

> a %>% 
    rename(my_type_1 = my_type_1_num_widgets, 
           my_type_2 = my_type_2_num_widgets) %>% 
    gather(type, num_widgets, my_type_1:my_type_2)
Source: local data frame [6 x 2]

       type num_widgets
1 my_type_1           1
2 my_type_1           2
3 my_type_1           3
4 my_type_2           4
5 my_type_2           5
6 my_type_2           6

Is there a way to do this in one step?

2

There are 2 answers

2
Steven Beaupré On BEST ANSWER

Try:

a %>% 
  gather(type, num_widgets) %>% ## gather the "num_widgets" columns
  mutate(type = sub("_num_widgets", "", type)) ## remove the suffix

Which gives:

#Source: local data frame [6 x 2]
#
#       type num_widgets
#1 my_type_1           1
#2 my_type_1           2
#3 my_type_1           3
#4 my_type_2           4
#5 my_type_2           5
#6 my_type_2           6
0
moodymudskipper On

since tidyr 1.0.0 you can do:

library(tidyverse)
a <- tibble(my_type_1_num_widgets = c(1, 2, 3), my_type_2_num_widgets = c(4, 5, 6))


pivot_longer(a, everything(), 
             names_to = c("type",".value"), 
             names_pattern = "(.*?)_(num_widgets)") %>%
  arrange(type)
#> # A tibble: 6 x 2
#>   type      num_widgets
#>   <chr>           <dbl>
#> 1 my_type_1           1
#> 2 my_type_1           2
#> 3 my_type_1           3
#> 4 my_type_2           4
#> 5 my_type_2           5
#> 6 my_type_2           6

Created on 2019-09-19 by the reprex package (v0.3.0)