gpt4 book ai didi

返回top_n后的原始数据集

转载 作者:行者123 更新时间:2023-12-04 11:28:17 25 4
gpt4 key购买 nike

给定一个数据集,我们可以使用 top_n 来限制我们在 tidyverse 中返回的行数(即排序/排名)。我喜欢大多数 tidyverse 操作的灵活性,因为它们在大多数情况下可以撤消,即您可以回到开始的地方。

使用这里问题中的数据和可能的解决方案(我写的),我怎样才能最好地撤消 top_n

数据 :

df<-structure(list(milk = c(1L, 2L, 1L, 0L, 4L), bread = c(4L, 5L, 
2L, 1L, 10L), juice = c(3L, 4L, 6L, 5L, 2L), honey = c(1L, 2L,
0L, 3L, 1L), eggs = c(4L, 4L, 7L, 3L, 5L), beef = c(2L, 3L, 0L,
1L, 8L)), class = "data.frame", row.names = c(NA, -5L))

代码 :
df %>% 
gather(key,value) %>%
group_by(key) %>%
summarise(Sum=sum(value)) %>%
arrange(desc(Sum)) %>%
top_n(3,Sum) %>%
ungroup()

以上给了我这个:
# A tibble: 3 x 2
key Sum
<chr> <int>
1 eggs 23
2 bread 22
3 juice 20

现在我将(学习如何)做的是在不删除代码的情况下返回原始数据集,即以编程方式从 top_n 恢复:

自然想到了 spreading( res就是上面的结果):
 spread(res,key,Sum)
# A tibble: 1 x 3
bread eggs juice
<int> <int> <int>
1 22 23 20

但是,如何从那个或撤消 top_n 的替代解决方案着手(还)。我怎样才能最好地实现这一目标?

最佳答案

使用 pull 的类似想法,但方法略有不同:

library(tidyverse)

df %>%
summarise_all(sum) %>% # Your method of selecting
gather(key, val) %>% # top three columns
top_n(3) %>% #
arrange(-val) %>% #
pull(key) %>% # pull 'key'
select(df, .) # select cols from df by `.`

# eggs bread juice
#1 4 4 3
#2 4 5 4
#3 7 2 6
#4 3 1 5
#5 5 10 2

并且,从上一个问题中发展出想法:
df[, '['(names(sort(colSums(df), T)), 1:3)]

这给出了相同的结果。

关于返回top_n后的原始数据集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57230069/

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