markfairbanks / tidytable

Tidy interface to 'data.table'
https://markfairbanks.github.io/tidytable/
Other
450 stars 32 forks source link

Proper way to return value after setkey() in pipe? #824

Closed realzhang closed 1 month ago

realzhang commented 1 month ago

Hi Mark: I'd like to return value after setkey() in a pipe within a function, such as:

# method 1:
fun_name <- function(){
data.table(
  a = 1:3,
  b = 4:6,
  c = c("a", "a", "b")  %>% setkey(a) # do not return value;
}

# method 2:
fun_name <- function(){
data.table(
  a = 1:3,
  b = 4:6,
  c = c("a", "a", "b")  %>% setkey(a) %>% .[]  # return value;
}

# method 3:
fun_name <- function(){
data.table(
  a = 1:3,
  b = 4:6,
  c = c("a", "a", "b")  %>% setkey(a) %>% dt()  # return value with warnning: i and j are both missing so ignoring the other arguments. This warning will be upgraded to error in future.
}

How to make method 3 work without warning or error? I prefer to using tidytable over data.table style for consistence. Thank you!

markfairbanks commented 1 month ago

A couple things.

1 - An empty dt() should work with no warnings and I can fix that.

2 - tidytable doesn't work with data.table keys.

library(tidytable)
library(data.table)

df <- data.table(a = "a", b = "b", c = 1)

setkey(df, "a")

df %>% haskey()
#> [1] TRUE

as_tidytable(df) %>% haskey()
#> [1] FALSE