logo

Unpacking Data Structures in R 📂R

Unpacking Data Structures in R

Overview

When using various functions in R, you will often see helpful results printed out as shown below. The problem arises when you want to take these results as output to use them further rather than just viewing them.

Example

20181022\_174214.png

For instance, if you need the maximum value of the residuals as shown in the screenshot above, you could just manually read and use the value 15.9719. However, if you need to check the maximum residual multiple times, this manual method would be inefficient. In such cases, you can use the str() function to check the structure of the data.

20181022\_174242.png

The str() function is very useful as it tells you the data type, the general format, and the total number of elements. More importantly, it shows how to reference the data structures, so you can access the desired data even if it is not directly printed in the output. In this example, since we need the maximum value of the residuals, we can find it using the structure out$residuals.

20181022\_175001.png

You can confirm that this matches the result of the summary() output above.

Of course, there is no guarantee that what you are looking for can always be found this easily. However, knowing how to perform these manipulations can make a significant difference in your skill level.

Code

out<-lm(waiting~eruptions,data=faithful); summary(out)
 
str(out)
out[]
 
max(out$residuals)