1 Goal


The goal of this tutorial is to learn how to capture output that is sent to the console so it can be stored in a variable or stored in a text file. This could be useful if a void function like str prints to the console but returns no object to be stored.


2 Introduction


# Most functions in R returns an object that is printed if it's not stored 
# Example:
# We print the average of the vector c(1,2,3,4,5)
mean(1:5)
## [1] 3
# We can see that it's an object of numerical class
str(mean(1:5))
##  num 3
# Nothing is printed if the output is stored in variable
my_mean <- mean(1:5)

# But we can print now the value of the variable just typing the name of the variable
my_mean
## [1] 3

3 Void functions


# Sometimes variables don't return anything
str(my_mean)
##  num 3
# For example the str function prints on console but returns nothing
str(str(my_mean))
##  num 3
##  NULL
# So if we try to store it in a variable we get NULL
my_str <- str(my_mean)
##  num 3
my_str
## NULL

4 Capture output


# However we may need to save the structure of the variable in a text file or a variable
# We cannot do it directly because we have learnt that there is no variable back
my_str <- str(my_mean)
##  num 3
my_str
## NULL
# We can use the capture.output variable to save this information
str(my_mean)
##  num 3
my_str <- capture.output(str(my_mean))

# It is stored in character form
str(my_str)
##  chr " num 3"
my_str
## [1] " num 3"

5 Conclusion


In this tutorial we have learnt how to store information that goes to console without being saved into any variable.