[英]Stata - Generate all possible combinations
I need to find all possible combinations of the following variables, each containing a X number of observations我需要找到以下变量的所有可能组合,每个变量都包含 X 个观察值
Variable Obs可变观测值
eg (black, pink), (black, pink, yellow), (black, pink, yellow, red), (red, green).... Order is not important, so I must delete all the combinations that contain the same elements (black, pink) and (pink, black).例如(黑色,粉红色),(黑色,粉红色,黄色),(黑色,粉红色,黄色,红色),(红色,绿色)......顺序并不重要,所以我必须删除所有包含相同的组合元素(黑色,粉红色)和(粉红色,黑色)。
Also, at the end I would need to calculate the number of total observations per each combination.此外,最后我需要计算每个组合的总观察数。
What is the fastest method, which is also less prone to errors?什么是最快的方法,也不太容易出错?
I read about Tuples but I am not able to write the code myself.我阅读了有关元组的信息,但我无法自己编写代码。
You can use tuples
(to install ssc install tuples
), like this:您可以使用
tuples
(安装ssc install tuples
),如下所示:
tuples black pink yellow red green
scalar black=1
scalar pink=2
scalar yellow=6
scalar red=15
scalar green=17
forvalues i = 1/`ntuples' {
scalar sum = 0
foreach n of local tuple`i' {
scalar sum = sum + `n'
}
di "`tuple`i'': " sum
}
Output: Output:
green: 17
red: 15
yellow: 6
pink: 2
black: 1
red green: 32
yellow green: 23
yellow red: 21
pink green: 19
pink red: 17
pink yellow: 8
black green: 18
black red: 16
black yellow: 7
black pink: 3
yellow red green: 38
pink red green: 34
pink yellow green: 25
pink yellow red: 23
black red green: 33
black yellow green: 24
black yellow red: 22
black pink green: 20
black pink red: 18
black pink yellow: 9
pink yellow red green: 40
black yellow red green: 39
black pink red green: 35
black pink yellow green: 26
black pink yellow red: 24
black pink yellow red green: 41
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.