Sac*_*amp 4 r vectorization seq
我想完成两件事.首先,如果我有一个向量,1:5我想得到一个矩阵(或两个向量),表示这些元素的唯一组合,包括两倍相同的数字,但不包括重复.
现在我可以使用矩阵来做到这一点:
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
Run Code Online (Sandbox Code Playgroud)
但必须有一个更简单的方法.我试图用Vectorize的seq,但是这给了我一个错误:
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
Run Code Online (Sandbox Code Playgroud)
我要做的第二件事是如果我有一个包含向量的列表bar,以获得一个包含重复列表元素的向量,该向量等于该元素中元素的数量.我可以这样做:
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
Run Code Online (Sandbox Code Playgroud)
但同样必须有一个更简单的方法.我Vectorize在这里再次尝试,但同样的错误:
Vectorize(rep,"each")(1:length(bar),each=sapply(bar,length))
in Vectorize(rep, "each") :
must specify formal argument names to vectorize
Run Code Online (Sandbox Code Playgroud)
> unlist(lapply(1:5, seq, from=1))
[1] 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5
> unlist(lapply(1:5, seq, 5))
[1] 1 2 3 4 5 2 3 4 5 3 4 5 4 5 5
Run Code Online (Sandbox Code Playgroud)
和
> bar = lapply(1:5, seq, from=1)
> rep(seq_along(bar), sapply(bar, length))
[1] 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5
Run Code Online (Sandbox Code Playgroud)
关于你的第一个问题:combn()基础中的简单函数怎么样:
> 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
Run Code Online (Sandbox Code Playgroud)
如果你需要一个矩阵来安排你组成的那个,只需将它转换为t(),就像t(combn(1:5,2))
注意:这不会为您提供seq重复元素的组合,但您可以轻松地将它们添加到矩阵中.