【问题标题】:tidyr gather: simultaneously gather and rename key?tidyr 收集:同时收集和重命名密钥?
【发布时间】:2015-06-17 20:09:40
【问题描述】:

假设我有以下数据框:

> 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

我想做两件事:

  1. 收集“num_widgets”列。
  2. 重命名生成的键以删除“num_widgets”后缀。

我目前这样做的方式,以及我得到的正确/期望的输出:

> 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

有没有办法一步完成?

【问题讨论】:

    标签: r tidyr


    【解决方案1】:

    试试:

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

    这给出了:

    #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
    

    【讨论】:

    • 我认为 gather(a) %&gt;% mutate(key = sub("_num_widgets", "", key)) 会更短
    • @DavidArenburg 确实,但是你会得到默认的 key value 而不是 type num_widgets 就像 OP 所需的输出一样,但我将 gsub 更改为 sub,谢谢。
    【解决方案2】:

    因为 tidyr 1.0.0 你可以这样做:

    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
    

    reprex package (v0.3.0) 于 2019 年 9 月 19 日创建

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-14
      • 1970-01-01
      • 1970-01-01
      • 2017-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多