gpt4 book ai didi

r - tidyr 聚集 : simultaneously gather and rename key?

转载 作者:行者123 更新时间:2023-12-01 11:32:43 27 4
gpt4 key购买 nike

假设我有以下数据框:

> 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

有没有一种方法可以一步完成?

最佳答案

尝试:

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

关于r - tidyr 聚集 : simultaneously gather and rename key?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30901442/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com