r-lib / rray

Simple Arrays
https://rray.r-lib.org
GNU General Public License v3.0
130 stars 12 forks source link

Convert to and from tibbles #253

Open krlmlr opened 4 years ago

krlmlr commented 4 years ago

What's the best way to convert an rray to a long-form tibble? Currently, the best way I know is to do . %>% as.table() %>% as_tibble(.name_repair = "unique"), would you support as_tibble.rray() and as_rray.tibble()?

(By the same token, would you support as_rray.table()?)

library(tidyverse)
library(rray)

titanic_rray <-
  Titanic %>%
  unclass() %>% # FIXME: Should work without
  as_rray()

Titanic %>% # FIXME: Should work similarly with titanic_rray %>% ...
  as_tibble()
#> # A tibble: 32 x 5
#>    Class Sex    Age   Survived     n
#>    <chr> <chr>  <chr> <chr>    <dbl>
#>  1 1st   Male   Child No           0
#>  2 2nd   Male   Child No           0
#>  3 3rd   Male   Child No          35
#>  4 Crew  Male   Child No           0
#>  5 1st   Female Child No           0
#>  6 2nd   Female Child No           0
#>  7 3rd   Female Child No          17
#>  8 Crew  Female Child No           0
#>  9 1st   Male   Adult No         118
#> 10 2nd   Male   Adult No         154
#> # … with 22 more rows

Titanic %>%
  as_tibble() %>%
  xtabs(n ~ ., .) %>% # FIXME: Should work without these three lines
  as.table() %>%
  unclass() %>%
  as_rray()
#> <rray<dbl>[,2,2,2][4]>
#> , , Age = Adult, Survived = No
#> 
#>       Sex
#> Class  Female Male
#>   1st       4  118
#>   2nd      13  154
#>   3rd      89  387
#>   Crew      3  670
#> 
#> , , Age = Child, Survived = No
#> 
#>       Sex
#> Class  Female Male
#>   1st       0    0
#>   2nd       0    0
#>   3rd      17   35
#>   Crew      0    0
#> 
#> , , Age = Adult, Survived = Yes
#> 
#>       Sex
#> Class  Female Male
#>   1st     140   57
#>   2nd      80   14
#>   3rd      76   75
#>   Crew     20  192
#> 
#> , , Age = Child, Survived = Yes
#> 
#>       Sex
#> Class  Female Male
#>   1st       1    5
#>   2nd      13   11
#>   3rd      14   13
#>   Crew      0    0

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

juangomezduaso commented 4 years ago

As you can see in #19 it is planned for the future I think. I supose what you want could be something like: ta<-as_tibble(cbind(expand.grid(rray_dim_names(.)), desired_name<-as.vector(.))) with a propper management of dimnames's names