R – Structure of Data Frame

To get the structure of Data Frame, call str() function and pass the Data Frame as argument to the function.

In this tutorial, we will learn how to use str() function to get the structure of a Data Frame, with the help of examples.

Syntax

The syntax to call str() function to get the structure of Data Frame df is

</>
Copy
str(df)

str() function does not return anything. It just prints output to the terminal.

Examples

In the following program, we take a Data Frame in df, and find its structure using str() function.

Example.R

</>
Copy
df <- data.frame(a = c(41, 42, 43),
                    b = c(44, 45, 46))
str(df)

Output

'data.frame':	3 obs. of  2 variables:
 $ a: num  41 42 43
 $ b: num  44 45 46

As per the output, the Data Frame contains 3 objects, which are rows; and 2 variables, which are columns. Also the datatype of each column is displayed.

Now, let us take a Data Frame with four columns and three rows, where one of the column contains strings. We shall print the structure of this Data Frame using str() function.

Example.R

</>
Copy
df <- data.frame(a = c(41, 42, 43),
                 b = c(44, 45, 46),
                 c = c(47, 48, 49),
                 d = c("apple", "mango", "cherry"))
str(df)

Output

'data.frame':	3 obs. of  4 variables:
 $ a: num  41 42 43
 $ b: num  44 45 46
 $ c: num  47 48 49
 $ d: chr  "apple" "mango" "cherry"

Conclusion

In this R Tutorial, we learned to get the structure of an R Data Frame using str() function, with the help of examples.