Structure() Function in R with Example

If you want to understand the best aspects of the R language, you’ll need a sharp understanding of the basic data types and data structures and how to operate on those. Everything that exists in R is an object.

Structure() in R

The structure() function in R returns the given object with further attributes set. R structure() function is a simplistic yet robust function that describes a given object with given attributes.

Syntax

structure(.Data, …)

Parameters

.Data: an object which will have various attributes attached to it.

: attributes, specified in tag = value form, which will be attached to data.

It is possible to give the same tag more than once, in which case the last value assigned wins. As with other ways of assigning attributes, using tag = NULL removes the attribute tag from the .Data if it is present.

Example

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

Output

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

Creating a data frame using structure() function

To create a data frame, 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.

For example, define a list of elements and pass the list to the structure() function and class as a second 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 inbuilt 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

The structure() function use cases in R

  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 prepare it for data import.
  4. When creating many R environments and each has an independent dataset.
  5. It is useful for persisting data.

That is it for the structure() method in R Programming.

See also

dim() function in R

function in R

R Operators

Leave a Comment