在R中创建向量的不同值矩阵的有效方法 [英] Efficient way to create matrix of different value of a vector in R
本文介绍了在R中创建向量的不同值矩阵的有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从向量创建这样的矩阵:
I am trying to create a matrix like this from a vector:
vec =c(1, 2, 3)
> A
[,1] [,2] [,3] [,4] [,5]
[1,] 1 1 0 0 0
[2,] 1 2 1 0 0
[3,] 1 3 2 1 0
,并且每次矢量vec
的长度和值都在变化时.我该如何编写函数来创建此矩阵?
and each time the length and value of vector vec
is changing. How can I write a function to create this matrix?
推荐答案
我对这个问题有点迷茫,但是这一行
I'm a bit lost on the question, but this line
vec <- 1:3
embed(c(rep(0,length(vec)),vec),length(vec)+1)
...产生所需结果的最后一部分:
...produces the last part of your desired result:
[,1] [,2] [,3] [,4]
[1,] 1 0 0 0
[2,] 2 1 0 0
[3,] 3 2 1 0
然后您可以绑定到向量的第一个数字.
Which you can then bind to the first number of the vector.
cbind(vec[1],embed(c(rep(0,length(vec)),vec),length(vec)+1))
给予...
[,1] [,2] [,3] [,4] [,5]
[1,] 1 1 0 0 0
[2,] 1 2 1 0 0
[3,] 1 3 2 1 0
这篇关于在R中创建向量的不同值矩阵的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文