What is the attr() function in R?

Overview

The attr() function in R is used to determine or set a specific attribute of an object.

Syntax

attr(x, which, exact = FALSE)

attr(x, which) <- value

Parameters

The attr() function takes the following parameter values:

  • x: This represents an object whose attributes are to be accessed.
  • which: This represents a non-empty character string that specifies which attribute is to be accessed.
  • exact: This takes a logical value of whether the which value should be matched exactly or not.
  • value: This represents the new value of the attribute.

Code example

# creating an object
x <- 1:8
# setting a 2 by 4 matrix as an attribute to x
attr(x,"dim") <- c(2, 4)
# printing x
x

Code explanation

  • Line 2: We specify that x has numeric values starting from 1 and ending at 8.

  • Line 5: We define a 2 by 4 matrix as an attribute to x, using the attr() function.

  • Line 8: We print the value of x.

Free Resources