# Vector to Matrix. How to do it generally

**URL:** https://discourse.julialang.org/t/vector-to-matrix-how-to-do-it-generally/118579
**Category:** General Usage
**Tags:** dataframes, vector, matrices
**Created:** [August 24, 2024, 10:10pm UTC](https://discourse.julialang.org/t/vector-to-matrix-how-to-do-it-generally/118579 "2024-08-24T22:10:03Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![martin\_sanchez](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/martin_sanchez/32/207525_2.png) [@martin\_sanchez](https://discourse.julialang.org/u/martin_sanchez)
#### Post date: [August 24, 2024, 10:10pm UTC](https://discourse.julialang.org/t/vector-to-matrix-how-to-do-it-generally/118579/1 "2024-08-24T22:10:03Z")

</div>

I have a DataFrame, and I am creating a function that receives it, extracts a few columns and convert those columns into a matrix. I was using Matrix{T}(df) and it worked, but when the slected columns turn to be 1, it says

```julia
MethodError: no method matching (Matrix)(::Vector{Float64})

```

So I read and found that there is reshape function, but I might not always have a constant number of rows or columns. I know I could define the correspondent variables but isn’t there any more elegant solution? Isn’t there any function like Matrix() that can handle the case where I have only one column?

---

<div class="post-metadata">

### Author: ![jling](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jling/32/212909_2.png) [@jling](https://discourse.julialang.org/u/jling)
#### Post date: [August 24, 2024, 10:12pm UTC](https://discourse.julialang.org/t/vector-to-matrix-how-to-do-it-generally/118579/2 "2024-08-24T22:12:37Z")

</div>

```julia
julia> a = rand(3)
3-element Vector{Float64}:
 0.6747880727217347
 0.9481856547503953
 0.9435165126351607

julia> reshape(a, :, 1)
3×1 Matrix{Float64}:
 0.6747880727217347
 0.9481856547503953
 0.9435165126351607

```

---

<div class="post-metadata">

### Author: ![rafael.guerra](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rafael.guerra/32/216610_2.png) [@rafael.guerra](https://discourse.julialang.org/u/rafael.guerra)
#### Post date: [August 25, 2024, 9:25am UTC](https://discourse.julialang.org/t/vector-to-matrix-how-to-do-it-generally/118579/3 "2024-08-25T09:25:56Z")

</div>

One way is to index the dataframe columns using vectors:

```julia
using DataFrames
df = DataFrame(fill.(1:4, 10), :auto)
ix = ["x1"] # or: ix = [1]
Matrix(df[:, ix])
ix = ["x2", "x4"] # or: ix = [2, 4]
Matrix(df[:, ix])

```
