Built with Tutify.io

    AIStudyLabs

    Explain str() Function in R with Examples

    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.

    Key Points-

    <a id="h-r-str-function"></a>

    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.

    <a id="h-syntax-of-the-str-function"></a>

    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)
    

    <a id="h-parameters-of-str-function"></a>

    Parameters of str() Function

    Following are the parameters of the str() function.

    <a id="h-return-value"></a>

    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.

    <a id="h-using-r-str-on-a-vector"></a>

    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.

    <a id="h-using-str-on-a-list"></a>

    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 listand 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.

    <a id="h-using-r-str-on-a-data-frame"></a>

    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
    

    <a id="h-using-str-on-a-factor"></a>

    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
    

    <a id="h-using-str-on-a-matrix"></a>

    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
    

    <a id="h-using-str-get-nested-data-structures"></a>

    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
    

    <a id="h-get-the-structure-of-a-function"></a>

    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'
    

    <a id="h-conclusion"></a>

    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!!

    <a id="h-references"></a>

    References