How to Use Structure() Function in R

The structure() function in R is “used to describe a given object with given attributes.

Syntax

structure(.Data, …)

Parameters

  1. .Data: an object which will have various attributes attached to it.
  2. : attributes, specified in tag = value form, will be attached to data.

Example 1: How to use the structure() function

dt <- structure(1:6, dim = 2:3)
dt

Output

    [,1] [,2] [,3]
[1,]  1    3    5
[2,]  2    4    6

Example 2: Creating a data frame using the structure() function

To create a data frame, you can also use the “structure()” function. You need to pass the class parameter to the structure() function and assign the value data frame to that class parameter.

df <- structure(list(year = c(2016, 2017, 2018, 2019), 
               length_days = c(365.32, 366.41, 367.53, 368.95)),
 .Names = c("year", "days"),
 class = "data.frame",
 row.names = c(NA, -4L))

df

Output

   year   days
1  2016  365.32
2  2017  366.41
3  2018  367.53
4  2019  368.95

And we created a data frame using the structure() method.

You can find the structure of the built-in data set using the structure() method.

structure(BOD)

Output

  Time demand
1  1    8.3
2  2   10.3
3  3   19.0
4  4   16.0
5  5   15.6
6  7   19.8

Applications

  1. It is useful when creating a smaller dataset within the Jupyter Notebook (using Markdown).
  2. When creating datasets within your R code demo code(and not using external CSV / TXT / JSON files).
  3. When describing a given object with mixed data types (e.i.: data frame) and preparing it for data import.
  4. When creating many R environments and each has an independent dataset.
  5. It helps persist data.

That is it.

Leave a Comment