I’ve used textConnection in R for reading from strings. Only recently, I realized (duh!) that it may also be used for write functionality much like Python’s stringIO module. In this post I show some simple examples for how to use this functionality.
Reading from a text connection.
Probably the most common places we use a text connection for input is when using the scan command. In fact, scan provides a simple optional argument to handle this special case. The fact that read.table (and derivatives) rely on scan under the hood makes this usable there as well.
1 2 3 4 5 6 7 8 9 10 | |
I can’t think of any other cases where I have used this functionality personally. If you have any other common (or even exotic) use-cases where this was useful, let me know in the comments.
Writing out to a textConnection:
Consider the case where one may want to collect all output from the R console as text to parse for some further analysis. sink is a useful command in this case. One may need to use sink while bypassing the filesystem (perhaps on a diskless system?!). textConnection to the rescue.
Here is an example:
1 2 3 4 5 | |
Look at the mode and can write parts of the description above. Now let’s try actually writing to it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
Epilogue
Clearly, we have full capabilities to do IO to and from strings in R. However, the use-cases where string IO is the best idea still eludes me. I will love to hear from other users who have or may use this for some idea of their own.