Access Attributes of Data Object in R (2 Examples)
In this article, I’ll show how to create a list of attributes for a data object in the R programming language.
Table of contents:
Let’s do this:
Creating Example Data
Initially, we have to construct some example data:
data <- data.frame(x1 = 1:5, # Create example data object x2 = letters[1:5]) data # Print example data object
Have a look at the previous table. It shows that our exemplifying data contains five rows and two columns.
Example 1: Create List of Data Attributes Using attributes() Functions
In this example, I’ll illustrate how to get a list of attributes of a particular data object (i.e. a data frame).
Have a look at the following R code:
data_attr <- attributes(data) # Apply attributes function data_attr # Print list of attributes # $names # [1] "x1" "x2" # # $class # [1] "data.frame" # # $row.names # [1] 1 2 3 4 5
As you can see in the previously shown RStudio console output, we have created a new list called data_attr, which contains multiple attributes of our example data frame.
More precisely, we have returned the column names, the class, and the row.names of our data frame.
Example 2: Extract Certain Attribute of Data Object
In Example 2, I’ll show how to extract only on specific attribute of a data object.
More precisely, the following R code accesses the class attribute of a data object:
data_attr$class # Extract class attribute # [1] "data.frame"
As you can see, the class of our data object is the data.frame class.
Video, Further Resources & Summary
Would you like to know more about the extraction of a list of attributes from a data object? Then you may watch the following video on my YouTube channel. I’m showing the R syntax of this post in the video:
In addition, you may want to read the related articles on my website. I have released numerous articles on topics such as data objects, graphics in R, and dates.
- attr, attributes & structure Functions in R
- The dim Function in R
- Set Row & Column Names of Data with Unknown Dimension
- Introduction to R
Summary: In this article you have learned how to access a list of attributes for a certain data object in the R programming language. Please tell me about it in the comments section, in case you have any further questions.