Sink(): Output redirection failed in if-statement block

I have a data frame named raw, with columns mostly of type character, that I would like to inspect for data cleaning. I decided to send the unique values of each column as a list to a temporary text file, like this

 if (interactive()) {
      tmp <- tempfile(fileext = '.txt')
      sink(file = tmp)
      lapply(raw, unique)
      sink()
      file.show(tmp)
    }

When I run this code en bloc, the text file is not written to (it comes up blank), but if I step through the lines I get my desired result.

I thought of introducing some kind of delay with Sys.sleep() but that didn't work. I also read through the documentation of sink() but couldn't find anything related to this behaviour.

I asked this question over at Stack Overflow and it was suggested that I use capture.output() instead. This actually worked but I'm still curious to know why my initial code did not work.

When running code in the console, any result that it not explicitly made invisible will be printed. When you run the if block, only the last result will be shown (in this case, nothing, though file.show will open the document). You need to explicitly call print(...) to make sure something's printed.

That said, sink can be good for logging script progress, but it's not something to rely on for writing specific objects to files. writeLines is good for that.

if (interactive()) {
  tmp <- tempfile(fileext = '.txt')
  uniques <- lapply(raw, unique)
  writeLines(as.character(uniques), tmp)
  file.show(tmp)
}

The text file's contents will look like c("foo", "bar", ...), but hopefully that's good enough for checking.

Thanks a lot. That was very helpful.