将控制台输出从函数接收到 .txt 文件
Sink console output to .txt file from a function
我需要填充一个 .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))
我需要填充一个 .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))