• Post author:
  • Post category:R Programming
  • Post last modified:September 10, 2024
  • Reading time:12 mins read
You are currently viewing Explain str() Function in R with Examples

The str() function in R is designed to compactly display the internal structure of an R object, such as vectors, lists, data frames, matrices, factors, or more complex structures. It stands for “structure” and offers a concise summary that includes the object’s type, length, and a preview of its content, making it a valuable tool for understanding and debugging code. In this article, I will explain the str() function and demonstrate how its syntax, parameters, and usage can help us diagnose the internal structure of various R objects.

Advertisements

Key Points-

  • The str() function is primarily used to compactly display an R object’s structure, making it easier to understand and debug code.
  • It works with almost all types of R objects, including vectors, lists, data frames, matrices, arrays, factors, nested data structures, and functions.
  • The function provides an overview that includes the object’s type, length, and a brief preview of its content, which is crucial for quickly assessing the object’s structure.
  • By default, str() also displays the attributes of the object, such as the names of elements in a list or the column names and types in a data frame.
  • The width parameter can be set to control the width of the output, which is useful when working in environments with limited display space.
  • The str() function does not return a value; instead, it performs a side effect by printing the structure of the object directly to the console.
  • The function is widely compatible with different versions of R and can be used in various R environments, including RStudio and Jupyter notebooks.
  • This is particularly useful for understanding complex, hierarchical data structures in R.

R str() Function

The str() function is designed to give a concise and compact overview of the internal structure of an R object. It is a versatile function that can handle almost any type of object in R, including vectors, lists, data frames, matrices, factors, nested data structures, and even R functions. It helps you quickly understand the type, length, and content of the object without needing to print the entire object.

Syntax of the str() Function

Following is the syntax of the str() function.


# Syntax of the str() function
str(object, 
    max.level = 1, 
    vec.len = NULL, 
    give.attr = TRUE, 
    width = getOption("width"), 
    nest.lev = 0, 
    strict.width = NULL, 
    formatNum = NULL)

Parameters of str() Function

Following are the parameters of the str() function.

  • object: (Required)The R object whose structure we want to examine.
  • max.level: Limits the depth of recursion when displaying nested lists.
  • vec.len: Controls how many elements of a vector are shown.
  • give.attr: Whether to display attributes of the object.
  • width: Controls the width of the output.

Return Value

The str() function does not return any value (NULL). Instead, it prints a compact, human-readable summary of the object’s structure to the console. The primary purpose of str() is inspection and debugging, rather than data manipulation or analysis. The output structure typically includes the following:

Content Preview: A few elements of the object are provided to give a quick overview of its contents.

Type and Class: The initial part of the output indicates the object’s type (e.g., “numeric”, “character”) and class.

Length/Dimensions: The length is shown for vectors, while dimensions are displayed for data frames, matrices, and arrays.

Using R str() on a Vector

To compactly view the internal structure of a vector, you can pass it to the str() function. This will display the vector’s type, length, and a few of its elements. Let’s create a numeric vector and use this function to examine its internal structure.


# Get the internal structure of vector
# Create a vector
vec <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
print("Given vector:")
print(vec)
print("Get the internal structure of the given vector:")
int_str <- str(vec)

The above code shows that is a numeric vector with 12 elements, displaying the first few elements.

Yields below output.

str in r

Using str() on a List

You can use this function to get the overall structure of the lists, including the type and size of each element within the list, along with a brief preview of their content. Let’s create a list and pass it into this function to get the overall view of the passed list.


# Get the internal structure of list
# Create a list
list <- list(name = "Nick", age = 25, scores = c(80, 85, 90))
print("Given list:")
print(list)
print("Get the internal structure of the given list:")
int_str <- str(list)

Yields below output.

str in r

Using R str() on a Data Frame

Alternatively, you can use the str() function on data frames to obtain details about the number of observations (rows) and variables (columns), along with the type and a preview of the first few entries in each column. Let’s create a data frame and pass it into this function to compactly view its internal structure.


# Get the internal structure of a data frame
# Create a data frame
df <- data.frame(name = c("Nick", "Jhon"), age = c(25, 30), score = c(88, 92))
print("Given data frame:")
print(df)
print("Get the internal structure of the given data frame:")
int_str <- str(df)

# Output:
# [1] "Given data frame:"

#   name age score
# 1 Nick  25    88
# 2 Jhon  30    92

# [1] "Get the internal structure of the given data frame:"

# 'data.frame':	2 obs. of  3 variables:
#  $ name : chr  "Nick" "Jhon"
#  $ age  : num  25 30
#  $ score: num  88 92

Using str() on a Factor

To find out the internal structure of the factors you can use the str() function to display the levels and the underlying integer codes representing those levels.


# Get the internal structure of a factor
# Create a factor
fac <- factor(c("low", "medium", "high", "medium", "low"))
print("Given factor:")
print(fac)
print("Get the internal structure of the given factor:")
int_str <- str(fac)

# Output:
# [1] "Given factor:"

# [1] low    medium high   medium low   
# Levels: high low medium

# [1] "Get the internal structure of the given factor:"
# Factor w/ 3 levels "high","low","medium": 2 3 1 3 2

Using str() on a matrix

To examine the internal structure of a matrix, apply the str() function to it. This will display the matrix’s dimensions and provide a brief preview of the data in a multi-dimensional format. Let’s create a matrix and pass it into the function to gain an overall insight into its structure.


# Get the internal structure of a matrices
# Create a matrix
matrix <- matrix(1:9, nrow = 3)
print("Given matrix:")
print(matrix)
print("Get the internal structure of the given matrix:")
int_str <- str(matrix)

# Output:
# [1] "Given matrix:"
#      [,1] [,2] [,3]
# [1,]    1    4    7
# [2,]    2    5    8
# [3,]    3    6    9

# [1] "Get the internal structure of the given matrix:"
# int [1:3, 1:3] 1 2 3 4 5 6 7 8 9

Using str() Get Nested Data Structures

You can also get the internal structure of the nested data by using the str() function. Let’s create the nested list and apply this function to get a concise view of the hierarchy, types, and some elements within the nested list without displaying the entire structure in detail.


# Get internal structure of nested list
# Create a nested list
nested_list <- list(
  personal_info = list(
    name = list("Nick"),
    age = list(25)
  ),
  scores = list(c(80, 85, 90))
)

# Print the nested list structure
print("Nested list:")
print(nested_list)

# Get the internal structure of the nested list
print("Internal structure of the nested list:")
str(nested_list)

# Output:
# [1] "Nested list:"
# $personal_info
# $personal_info$name
# $personal_info$name[[1]]
# [1] "Nick"

# $personal_info$age
# $personal_info$age[[1]]
# [1] 25

# $scores
# $scores[[1]]
# [1] 80 85 90

# Get the internal structure of the nested list
# [1] "Internal structure of the nested list:"

# List of 2
#  $ personal_info:List of 2
#   ..$ name:List of 1
#   .. ..$ : chr "Nick"
#   ..$ age :List of 1
#   .. ..$ : num 25
#  $ scores       :List of 1
#   ..$ : num [1:3] 80 85 90

Get the Structure of a Function

Finally, you can use the str() function to get the internal structure of the function.


# Get internal structure of a function
# Create a function
fun <- function(x, y) { x + y }
str(fun)

# Output:
# function (x, y)  
#  - attr(*, "srcref")= 'srcref' int [1:8] 3 8 3 31 8 31 3 3
#  ..- attr(*, "srcfile")=Classes 'srcfilecopy', 'srcfile' <environment: 0x000001ab75f7ada8> 

Conclusion

In this article, I have explained how the str() function in R is a powerful tool for quickly and effectively understanding the internal structure of various objects such as vectors, matrices, lists, data frames, and factors. Its concise summary is extremely valuable for both beginners and advanced R users, especially when debugging or working with new datasets.

Happy Learning!!

References