问题描述
我想知道为什么只有在某些情况下,R 才会在将数据帧/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
传入 tidy
和 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
请注意,我不在乎我的输出不是小标题。无论如何,我更喜欢使用 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] 不再打印,#869 和 #1122。添加了测试。为了让它起作用,我们不得不忍受一个缺点:如果 := 在函数结束之前没有 DT[] 的函数中使用,那么下一次 DT 或 print(DT) 被输入到提示,不会打印任何内容。将打印重复的 DT 或 print(DT)。为避免这种情况:在函数中的最后一个 := 之后包含一个 DT[]。