[SOLVED] R: How would you convert a matrix into a list with a single element?

Issue

Data:

input1 <- matrix(c(2, 15))
input2 <- list(5, integer(0), c(5, 6))

I have a matrix (input1) that looks like this:

         [,1]
[1,]    2
[2,]   15

I want to convert it into a list object that looks like this:

[[1]]
[1] 2 15

What’s the best way of doing this?

It would also be useful if the function could take a list like this (input2) as an input and not make any changes to it:

[[1]]
[1] 5

[[2]]
integer(0)

[[3]]
[1]  5 16

[[4]]
[1] 9

[[5]]
integer(0)

Solution

Here’s a function to do that –

change_matrix_to_list <- function(x) {
  if(inherits(x, 'matrix')) list(c(x))
  else x
}

input1 <- matrix(c(2, 15))
input2 <- list(5, integer(0), c(5, 6))

change_matrix_to_list(input1)

#[[1]]
#[1]  2 15

change_matrix_to_list(input2)

#[[1]]
#[1] 5

#[[2]]
#integer(0)

#[[3]]
#[1] 5 6

This checks if the input has a class 'matrix' then change it to list or else keep it as it is.

Answered By – Ronak Shah

Answer Checked By – Gilberto Lyons (BugsFixing Admin)

Leave a Reply

Your email address will not be published.