在 R 中向量化 rep 和 seq [英] Vectorizing rep and seq in R
问题描述
我正在努力完成两件事.首先,如果我有一个向量 1:5
我想得到一个矩阵(或两个向量),指示这些元素的唯一组合,包括两倍相同的数字但不包括重复.
I am trying to accomplish two things. First if I have a vector 1:5
I want to get a matrix (or two vectors) indicating the unique combinations of these elements including twice the same number but excluding repetitions.
现在我可以使用矩阵来做到这一点:
Right now I can do this using a matrix:
foo <- matrix(1:5,5,5)
cbind(foo[upper.tri(foo,diag=TRUE)],foo[lower.tri(foo,diag=TRUE)])
[,1] [,2]
[1,] 1 1
[2,] 1 2
[3,] 2 3
[4,] 1 4
[5,] 2 5
[6,] 3 2
[7,] 1 3
[8,] 2 4
[9,] 3 5
[10,] 4 3
[11,] 1 4
[12,] 2 5
[13,] 3 4
[14,] 4 5
[15,] 5 5
但必须有更简单的方法.我试图在 seq
上使用 Vectorize
但这给了我一个错误:
But there has to be a simpler way. I tried to use Vectorize
on seq
but this gives me an error:
cbind(Vectorize(seq,"from")(1:5,5),Vectorize(seq,"to")(5,1:5))
Error in Vectorize(seq, "from") :
must specify formal argument names to vectorize
我想做的第二件事是,如果我有一个包含向量的列表,bar
,以获得一个包含重复的列表元素的向量,该元素的数量等于该元素中的元素数.我可以这样做:
A second thing I want to do is if I have a list containing vectors, bar
, to get a vector containing the elements of the list repeated equal to the number of elements in that element. I can do this with:
unlist(apply(rbind(1:length(bar),sapply(bar,length)),2,function(x)rep(x[1],x[2])))
[1] 1 1 1 1 1 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3
但同样必须有更简单的方法.我在这里再次尝试了 Vectorize
但出现了同样的错误:
But again there must be an easier way. I tried Vectorize
again here but with the same error:
Vectorize(rep,"each")(1:length(bar),each=sapply(bar,length))
in Vectorize(rep, "each") :
must specify formal argument names to vectorize
推荐答案
对于你的第一个问题:base 中简单的 combn()
函数怎么样:
To your first question: what about the simple combn()
function in base:
> combn(1:5,2)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 1 1 1 1 2 2 2 3 3 4
[2,] 2 3 4 5 3 4 5 4 5 5
如果你需要一个矩阵排列你所组成的矩阵,只需用t()
转置它,比如t(combn(1:5,2))
If you need a matrix arranged the one you made up, just transpose it with t()
, like t(combn(1:5,2))
注意:这将不会返回序列中重复元素的组合,但您可以轻松地将它们添加到矩阵中.
Note: this will not give you back the combinations of repeated elements of your seq, but you may add those easily to the matrix.
这篇关于在 R 中向量化 rep 和 seq的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!