1

I am wondering why only in some instances R produces the output of the data frame/tibble on the console after piping it into a function. Below is a reproducible example.

I first define a custom function called make_stars() because I would like to see stars associated with significance in my regression output.

library(data.table)
library(dplyr)
library(broom)
library(fixest)

# Define custom function to create stars within the broom output
make_stars <- function(tidy_DT) {
  data.table::setDT(tidy_DT)
  tidy_DT <- tidy_DT %>%
    .[p.value <= 0.01, stars := "***"] %>%
    .[p.value > 0.01 & p.value <= 0.05, stars := "**"] %>%
    .[p.value >0.05 & p.value <= 0.10, stars := "*"]

  return(tidy_DT)
}

Now, to show exactly what I mean, notice that in the first case, I pipe the OLS_model object only into tidy and the result appears on the Console and after the RMarkdown chunk. However, this does not happen if I pipe OLS_model into both tidy and make_stars.


DT <- iris

OLS_model <-
  DT %>%            # Pipes in a dataset into a function
  feols(
  Sepal.Length ~ Sepal.Width + Petal.Length,  
  data = .         # Puts the . in here to indicate where the data.table is going 
)

# Output is displayed
OLS_model %>% tidy 

# Output is NOT displayed
OLS_model %>% tidy %>% make_stars

Note that I don't care that my output is not a tibble. I prefer using a data.table anyways.

Thanks!

1 Answers1

0

We could add [] at the end

make_stars <- function(tidy_DT) {
 data.table::setDT(tidy_DT)
 tidy_DT <- tidy_DT %>%
  .[p.value <= 0.01, stars := "***"] %>%
 .[p.value > 0.01 & p.value <= 0.05, stars := "**"] %>%
   .[p.value >0.05 & p.value <= 0.10, stars := "*"][]

 return(tidy_DT)
 }

Or the output can be assigned to an object

out <- OLS_model %>% 
            tidy %>%
            make_stars
out

The behavior is mentioned in the bugfixes here

if (TRUE) DT[,LHS:=RHS] no longer prints, #869 and #1122. Tests added. To get this to work we've had to live with one downside: if a := is used inside a function with no DT[] before the end of the function, then the next time DT or print(DT) is typed at the prompt, nothing will be printed. A repeated DT or print(DT) will print. To avoid this: include a DT[] after the last := in your function.

akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thanks for the solution. Do you know the reason why this works? And in general, why R displays the output in some cases and not others? Thank you very much. – plausibly_exogenous Mar 21 '21 at 18:42
  • @plausibly_exogenous it is because of `:=` i.e. `as.data.table(iris)[, new := 1]` doesn't print the output to the console, but `as.data.table(iris)[, new := 1][]` returns the data printed. – akrun Mar 21 '21 at 18:42