Is it possible to make R function satisfy the following:
Return a list and only print the first element. (I know how to do it)
Assign step 1 result to a new object with class of the first element, then I can use pipe function and other
dplyrfunctions directly.The new object still contain the original list elements.
For example,
my_tbl <- function(x) {
dat <- tibble(num = x)
words <- paste("input is", x)
res <- list(dat = dat, words = words)
class(res) <- c("myclass", "list")
return(res)
}
print.myclass <- function(x) {
print(x[[1]])
invisible(x)
}
a <- my_tbl(1:2)
a
# A tibble: 2 × 1
num
<int>
1 1
2 2
> a$words
[1] "input is 1" "input is 2"
a$dat %>%
mutate(b = 3)
# A tibble: 2 × 2
num b
<int> <dbl>
1 1 3
2 2 3
Is it possible to use dplyr functions, eg. mutate, directly without adding any intermediate steps, eg.a$dat, to have to same result? like this:
a %>%
mutate(b = 3)
# A tibble: 2 × 2
num b
<int> <dbl>
1 1 3
2 2 3