【问题标题】:Sink console output to .txt file from a function将控制台输出从函数接收到 .txt 文件
【发布时间】:2019-12-26 16:29:39
【问题描述】:

在运行具有嵌套函数的代码时,我需要填充一个 .txt 文件。我为此使用sink()。输出包括 a) 文本消息,b) 数据帧行。我无法从嵌套函数内部打印数据帧:

sink("log.txt")

cat("Some message")          # Successfully prints to log.txt
head(some_df)                # Successfully prints to log.txt

some_fun = function(x){
    # ...
    cat("Another message")   # Successfully prints to log.txt
    head(another_df)         # Nothing gets printed to log.txt
    # check that another_df is not empty:
    cat(nrow(another_df))    # Successfully prints to log.txt (>0) 
    # ...
}
some_fun(x=0)

sink()

那么正确的做法是什么?

【问题讨论】:

  • 像这样将print 包裹在head 周围:print(head(another_df))。那么它应该可以工作..
  • 并包含"\n"作为每个cat()中的最后一个字符串。
  • 非常感谢@samadhi。我是个白痴,尝试过更复杂的 cat() 和 print() 组合。
  • 很高兴能帮上忙。

标签: r dataframe output cat sink


【解决方案1】:

在你的函数中包裹一个print 围绕head。像这样:

print(head(another_df))

【讨论】:

    猜你喜欢
    • 2021-06-20
    • 1970-01-01
    • 1970-01-01
    • 2016-03-29
    • 2023-03-16
    • 2023-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多