【问题标题】:Obtain all possible sums and output list based on values根据值获取所有可能的总和和输出列表
【发布时间】:2020-02-05 16:50:45
【问题描述】:

我有一个包含两列的数据框:LOOKUP 包含一个索引号,另一列 VALUE 包含一个与该数字关联的字符串:

LOOKUP    VALUE
1000      Apple
100       Banana
10        Grape
1         Orange

如下R代码所示:

dat <- data.frame(LOOKUP= c(1000, 100, 10, 1),
                  VALUE = c("Apple", "Banana", "Grape", "Orange"))

在此示例中,查找值有 15 个可能的总和:

  • 4 个总和,其中只有一个数字相加 (1000, 100, 10, 1)
  • 两个数的 6 和(1000 + 100, 1000 + 10, 1000 + 1, 100 + 10, 100 + 1, 10 + 1)
  • 三个数的 4 和(1000 + 100 + 10、1000 + 100 + 1、1000 + 10 + 1、100 + 10 + 1)
  • 四个数之和(1000 + 100 + 10 + 1)

由于缺乏更好的描述,这些总和用于理解购物车中有什么水果。例如,如果 sum = 1100,我们知道购物车有一个苹果和一个香蕉。有谁知道我会如何为我的集合中的所有可能组合做到这一点?我想要的输出是一个新的数据框:

SUM    VALUES
1111   Apple, Banana, Grape, Orange
...
1100   Apple, Banana
...
11     Grape, Orange
1      Apple

【问题讨论】:

标签: r combinations


【解决方案1】:

涉及purrrtibbledplyrtidyr 的解决方案可能是:

map(.x = 1:nrow(dat), ~ combn(dat$VALUE, .x, paste, collapse = ",") %>%
     enframe()) %>%
 bind_rows() %>%
 rowid_to_column() %>%
 separate_rows(value) %>%
 left_join(dat, by = c("value" = "VALUE")) %>%
 group_by(rowid) %>%
 summarise(comb = toString(value),
           sum = sum(LOOKUP))

  rowid comb                           sum
   <int> <chr>                        <dbl>
 1     1 Apple                         1000
 2     2 Banana                         100
 3     3 Grape                           10
 4     4 Orange                           1
 5     5 Apple, Banana                 1100
 6     6 Apple, Grape                  1010
 7     7 Apple, Orange                 1001
 8     8 Banana, Grape                  110
 9     9 Banana, Orange                 101
10    10 Grape, Orange                   11
11    11 Apple, Banana, Grape          1110
12    12 Apple, Banana, Orange         1101
13    13 Apple, Grape, Orange          1011
14    14 Banana, Grape, Orange          111
15    15 Apple, Banana, Grape, Orange  1111

样本数据:

dat <- data.frame(LOOKUP= c(1000, 100, 10, 1),
                  VALUE = c("Apple", "Banana", "Grape", "Orange"),
                  stringsAsFactors = FALSE)

【讨论】:

  • 非常感谢!我正在尝试运行您的代码,但收到以下错误消息:'类中的错误(out)
  • 我在导入数据时使用了stringsAsFactors = FALSE。请查看更新后的帖子。
  • 你是个传奇。非常感谢。只是提醒一下,我认为需要将“Tibble”添加到您所需的库列表中。我需要为enframe加载它。再次感谢:)
  • 你说得对,我一直认为它是 dplyr 的一部分 :) 很高兴它有帮助!
猜你喜欢
  • 1970-01-01
  • 2017-09-03
  • 1970-01-01
  • 2016-06-03
  • 2022-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-18
相关资源
最近更新 更多