# Vectors from while loop to matrix

Hi,
I have a problem with my program in R.
I have "while" loop. From these loop i have vectors "a:k", where a and k are parametres / variables. I need these vectors in one matrix. However i tried, i have or one matrix from lats vector from loop or single matrixs from one vector.. I tried created matrix also in loop while also after while.
I have it :

``````f1=function (c)

{ l = length(c)
i=0
while (i<l)
{i=i+1}
for (e in 0:((l+1)/2))
{a=0
k=(((l-1)/2)-e)
while ((a<=(((l-1)/2)-e)) & (k<=(l-e)))
{a=a+1
k=k+1
print(c[a:k])
print("aaa")
}}
print (matrix(c[a:k]))}
``````

## I need to create few matrix"s from vectors which have these same length.

Hi, and welcome!

You've got an essential part right -- the vectors need to be of equal length. And, of course, a matrix can't mix characters and numeric the way a data frame can.

Loops have their place, but often a more direct approach is preferable.

Consider this reproducible example, called a reprex

``````vector1 <- seq(1,10,1)
vector2 <- seq(11,20,1)
vector3 <- seq(21,30,1)
vectors <- cbind(vector1, vector2, vector3)
vectors
#>       vector1 vector2 vector3
#>  [1,]       1      11      21
#>  [2,]       2      12      22
#>  [3,]       3      13      23
#>  [4,]       4      14      24
#>  [5,]       5      15      25
#>  [6,]       6      16      26
#>  [7,]       7      17      27
#>  [8,]       8      18      28
#>  [9,]       9      19      29
#> [10,]      10      20      30
class(vectors)
#> [1] "matrix"
``````

Created on 2019-12-21 by the reprex package (v0.3.0)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.