Zuooo
Zuooo

Reputation: 337

How to transform a tibble to array?

Take diamonds data as an example:

library(tidyverse)
data <- diamonds %>% select(x, y)

There are 53940 rows and 2 columns of data; how to transform that to an array with [1:53940, 1, 1, 1:2] dim?

Upvotes: 0

Views: 1216

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 269481

1) array Use data.matrix and array:

a <- diamonds %>% 
  select(x, y) %>% 
  data.matrix %>% 
  array(c(nrow(.), 1, 1, ncol(.)))

str(a)
## num [1:53940, 1, 1, 1:2] 3.95 3.89 4.05 4.2 4.34 3.94 3.95 4.07 3.87 4 ...

2) abind Another approach is the abind package.

library(abind)

a2 <- diamonds %>%
  select(x, y) %>%
  abind(along = 1.5) %>%
  abind(along = 1.5)

str(a2)
## num [1:53940, 1, 1, 1:2] 3.95 3.89 4.05 4.2 4.34 3.94 3.95 4.07 3.87 4 ...
##  - attr(*, "dimnames")=List of 4
##   ..$ : NULL
##   ..$ : NULL
##   ..$ : NULL
##   ..$ : chr [1:2] "x" "y"

identical(a, unname(a2))
## [1] TRUE

Upvotes: 1

Related Questions