tidyr 收集:同时收集和重命名密钥? [英] tidyr gather: simultaneously gather and rename key?

查看:29
本文介绍了tidyr 收集:同时收集和重命名密钥?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下数据框:

> 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"后缀.

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

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?

推荐答案

尝试:

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

这篇关于tidyr 收集:同时收集和重命名密钥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆