expand.grid的非冗余版本 [英] Non-redundant version of expand.grid
问题描述
R
函数 expand.grid
返回提供的参数元素之间的所有可能组合。例如,
The R
function expand.grid
returns all possible combination between the elements of supplied parameters. e.g.
> expand.grid(c("aa", "ab", "cc"), c("aa", "ab", "cc"))
Var1 Var2
1 aa aa
2 ab aa
3 cc aa
4 aa ab
5 ab ab
6 cc ab
7 aa cc
8 ab cc
9 cc cc
您知道一种直接获取有效的方法的方法(因此在<$之后无需进行任何行比较c $ c> expand.grid )仅提供的向量之间的唯一组合?输出将为
Do you know an efficient way to get directly (so without any row comparison after expand.grid
) only the 'unique' combinations between the supplied vectors? The output will be
Var1 Var2
1 aa aa
2 ab aa
3 cc aa
5 ab ab
6 cc ab
9 cc cc
编辑最终可以从答案中删除每个元素与其自身的组合。即使(数学上) aa aa
在 Var1 <的一个元素之间是(常规)唯一组合,我实际上也不在程序中使用它/ code>和另一个
var2
。
EDIT the combination of each element with itself could be eventually discarded from the answer. I don't actually need it in my program even though (mathematically) aa aa
would be one (regular) unique combination between one element of Var1
and another of var2
.
该解决方案需要从两个向量中生成元素对(即每个输入向量中的一个-以便可以将其应用于2个以上输入)
The solution needs to produce pairs of elements from both vectors (i.e. one from each of the input vectors - so that it could be applied to more than 2 inputs)
推荐答案
如何使用外部
?但是这个特殊的函数将它们连接成一个字符串。
How about using outer
? But this particular function concatenates them into one character string.
outer( c("aa", "ab", "cc"), c("aa", "ab", "cc") , "paste" )
# [,1] [,2] [,3]
#[1,] "aa aa" "aa ab" "aa cc"
#[2,] "ab aa" "ab ab" "ab cc"
#[3,] "cc aa" "cc ab" "cc cc"
您也可以在 combn
上使用如果不想重复元素,则是两个向量的唯一元素(例如 aa aa
)
You can also use combn
on the unique elements of the two vectors if you don't want the repeating elements (e.g. aa aa
)
vals <- c( c("aa", "ab", "cc"), c("aa", "ab", "cc") )
vals <- unique( vals )
combn( vals , 2 )
# [,1] [,2] [,3]
#[1,] "aa" "aa" "ab"
#[2,] "ab" "cc" "cc"
这篇关于expand.grid的非冗余版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!