Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Convert array to matrix with one row

Given foo and mock, is there a way to have foo as class matrix instead of array?

Calling as.matrix() puts foo into a wrong structure. I would like to have foo being a matrix, just with one row instead of two.

foo = structure(c(0.729504668890744, 0.190464932275543, 0.0800303988337127), 
              .Dim = c(1L, 3L, 1L), 
              .Dimnames = list(NULL, c("A", "B", 
                                       "C"), "NA"))
class(foo[, , 1L])
#> [1] "numeric"
print(foo[, , 1L])
#>         A         B         C 
#> 0.7295047 0.1904649 0.0800304


mock = structure(c(0.550876469322338, 0.729504668890744, 0.342833178276825, 
                 0.190464932275543, 0.106290352400837, 0.0800303988337127), 
               .Dim = c(2L, 
                        3L, 1L), 
               .Dimnames = list(NULL, c("A", "B", "C"), 
                                "NA"))

class(mock[, , 1L])
#> [1] "matrix"
print(mock[, , 1L])
#>              A         B         C
#> [1,] 0.5508765 0.3428332 0.1062904
#> [2,] 0.7295047 0.1904649 0.0800304

# matrix conversion does not result in desired structure

as.matrix(foo[, , 1L])
#>        [,1]
#> A 0.7295047
#> B 0.1904649
#> C 0.0800304

Created on 2019-11-04 by the reprex package (v0.3.0)

like image 879
pat-s Avatar asked Nov 25 '25 02:11

pat-s


2 Answers

You can use matrix transpose, base::t():

t(foo[,,1L])
#>              A         B         C
#> [1,] 0.7295047 0.1904649 0.0800304

class(t(foo[,,1L]))
#> [1] "matrix"
like image 176
M-- Avatar answered Nov 27 '25 17:11

M--


Here is an option with array

array(c(foo), dim(foo)[-3], dimnames = dimnames(foo)[1:2])
like image 26
akrun Avatar answered Nov 27 '25 16:11

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!