通过自定义函数进行管道传输后数据 frame/output 未显示

Data frame/output not displaying after piping through custom function

我想知道为什么仅在某些情况下,R 在将数据通过管道传输到函数后才在控制台上生成数据的输出 frame/tibble。下面是一个可重现的例子。

我首先定义了一个名为 make_stars() 的自定义函数,因为我希望在我的回归输出中看到与显着性相关的星星。

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)
}

现在,为了准确说明我的意思,请注意在第一种情况下,我仅将 OLS_model 对象通过管道传输到 tidy 中,结果显示在控制台上 并且 在 RMarkdown 块之后。但是,如果我将 OLS_model 管道传输到 both tidymake_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

请注意,我不在乎我的输出不是 tibble。无论如何,我更喜欢使用 data.table。

谢谢!

我们可以在末尾添加[]

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)
 }

或者输出可以赋值给一个对象

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

错误修复中提到了该行为 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.