如何将 tibble 转换为数组?

How to transform a tibble to array?

diamonds数据为例:

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

53940 rows2 columns条数据;如何将其转换为 [1:53940, 1, 1, 1:2] dim?

的数组

1) 数组 使用data.matrixarray:

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 另一种方法是 abind 包。

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