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.
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.
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]
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
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)))