Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make an R function to turn a vector into a matrix?

I am just learning R and got to functions. I have made a function of 0 or more variables, but they always return one value. I can make a function that returns a vector of values using c(x,y,z), but when I input a vector, it just returns a longer vector. For example if I make a function f <- function(x) { c(x, x^2, x^3) } and pass it 2, it returns 2, 4, 8. But if i pass it the vector 2,3,4, it returns 2,4,8,3,9,27,4,16,64. Where I would like a matrix with 3 rows corresponding to the 3 inputs I gave it, and 3 columns with the return values. So a 3×3 matrix with the columns (2,3,4),(4,9,16),(8,27,64). I would also love to be able to do this using base functionality, although if I have to use a package to do this that would also be fine

tried input (2,3,4). wanted output:

2   4   8
3   9  27
4  16  64

but got (2,4,8,3,9,27,4,16,64).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Using matrix(), with nrow set to the length of the input vector:

f <- function(x) {
  matrix(c(x, x^2, x^3), nrow = length(x))
} 

f(c(2, 3, 4))

#>      [,1] [,2] [,3]
#> [1,]    2    4    8
#> [2,]    3    9   27
#> [3,]    4   16   64

Created on 2022-11-11 with reprex v2.0.2

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading