我有一个货币符号列表,但它们成对出现,并且不能违背自己。以下是一个例子:
ccy <- c("USD","EUR","JPY","GBP","CAD","AUD","NZD","CHF","NOK","SEK")
g <- expand.grid(ccy,ccy)
g <- g[g[,1]!=g[,2],]
但美元兑欧元,正好是欧元兑美元的反转,或欧元兑日元正好与日元兑欧元相反,所以我想从{{1 }}
是否有一种编程方式只从列表中获取唯一对?
答案 0 :(得分:4)
使用combn()
:
combn(ccy, 2)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15] [,16]
[1,] "USD" "USD" "USD" "USD" "USD" "USD" "USD" "USD" "USD" "EUR" "EUR" "EUR" "EUR" "EUR" "EUR" "EUR"
[2,] "EUR" "JPY" "GBP" "CAD" "AUD" "NZD" "CHF" "NOK" "SEK" "JPY" "GBP" "CAD" "AUD" "NZD" "CHF" "NOK"
[,17] [,18] [,19] [,20] [,21] [,22] [,23] [,24] [,25] [,26] [,27] [,28] [,29] [,30] [,31] [,32]
[1,] "EUR" "JPY" "JPY" "JPY" "JPY" "JPY" "JPY" "JPY" "GBP" "GBP" "GBP" "GBP" "GBP" "GBP" "CAD" "CAD"
[2,] "SEK" "GBP" "CAD" "AUD" "NZD" "CHF" "NOK" "SEK" "CAD" "AUD" "NZD" "CHF" "NOK" "SEK" "AUD" "NZD"
[,33] [,34] [,35] [,36] [,37] [,38] [,39] [,40] [,41] [,42] [,43] [,44] [,45]
[1,] "CAD" "CAD" "CAD" "AUD" "AUD" "AUD" "AUD" "NZD" "NZD" "NZD" "CHF" "CHF" "NOK"
[2,] "CHF" "NOK" "SEK" "NZD" "CHF" "NOK" "SEK" "CHF" "NOK" "SEK" "NOK" "SEK" "SEK"
函数combn
从输入向量生成长度为n
的所有唯一组合。
有关详细信息,请参阅?combn
。