3

I would like to create a list of all combinations of A, B, and C such that A+B+C=100 This list should be as following.

 A  B  C    
 0  0 100
100 0  0
 99 1  0
 98 2  0
 99 0  1

I don't know how to approach this problem in R.

M--
  • 25,431
  • 8
  • 61
  • 93
iheb68200
  • 31
  • 1

3 Answers3

3

We can use complete to generate all the combinations and then do a filter

library(dplyr)
library(tidyr)
complete(df1, A, B, C) %>% 
      filter((A + B + C) == 100)

Or using crossjoin

library(data.table)
setDT(df1)[, CJ(A, B, C, unique = TRUE)][(A + B + C) == 100]
akrun
  • 874,273
  • 37
  • 540
  • 662
2

A base R option using expand.grid + rowSums + subset

out <- subset(
  s <- with(df,expand.grid(A, B, C)),
  rowSums(s) == 100
)

or

out <- subset(
  s <- do.call(expand.grid,df),
  rowSums(s) == 100
)

and you will see

> nrow(out)
[1] 5151
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
2
library(tidyr)
library(dplyr)

If you want unique combinations this works:

with(dfa, crossing(A, B, C)) %>%
  filter(rowSums(.) == 100)

If you need all the combinations, then try this:

with(dfa, expand.grid(A, B, C)) %>%
  filter(rowSums(.) == 100) %>% 
  rename_all(list(~names(dfa)))
M--
  • 25,431
  • 8
  • 61
  • 93