Trusted answers to developer questions

What is the assign() function in R?

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

Overview

The assign() function in R is simply used to assign a value to a name in an environment.

Syntax

assign(x, value, pos = -1, envir = as.environment(pos),
       inherits = FALSE, immediate = TRUE)

Required parameter values

The assign() function takes the following mandatory parameter values:

  • x: This represents the variable name that is given as a character string.
  • value: This is the value to be assigned to the x variable.

Optional parameter values

The assign() function takes the following optional parameter values:

  • pos: This represents where to do the assignment. By default, it is done in the current environment.
  • envir: This represents the environment.
  • inherits: This is used in case the enclosing frames of the environment need to be inspected or not.
  • immediate: This is an ignored compatibility feature.

Code example

# using the assign() function
assign('x', 'Theo')
x
# using the assign() function
assign(x, 42)
Theo

Code explanation

  • Line 2: We use the assign() function to assign the value "Theo" to the variable name x.
  • Line 6: We use the assign() function to assign the value 42 to the variable x, which is already the same as Theo in the environment.
  • Line 7: We print the variable Theo.

RELATED TAGS

function
r

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
Did you find this helpful?