R Cran Print Table Assignments

assign {base}R Documentation

Assign a Value to a Name


Assign a value to a name in an environment.


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


a variable name, given as a character string. No coercion is done, and the first element of a character vector of length greater than one will be used, with a warning.

a value to be assigned to .

where to do the assignment. By default, assigns into the current environment. See ‘Details’ for other possibilities.

the to use. See ‘Details’.

should the enclosing frames of the environment be inspected?

an ignored compatibility feature.


There are no restrictions on the name given as : it can be a non-syntactic name (see ).

The argument can specify the environment in which to assign the object in any of several ways: as (the default), as a positive integer (the position in the list); as the character string name of an element in the search list; or as an (including using to access the currently active function calls). The argument is an alternative way to specify an environment, but is primarily for back compatibility.

does not dispatch assignment methods, so it cannot be used to set elements of vectors, names, attributes, etc.

Note that assignment to an attached list or data frame changes the attached copy and not the original object: see and .


This function is invoked for its side effect, which is assigning to the variable . If no is specified, then the assignment takes place in the currently active environment.

If is , enclosing environments of the supplied environment are searched until the variable is encountered. The value is then assigned in the environment in which the variable is encountered (provided that the binding is not locked: see : if it is, an error is signaled). If the symbol is not encountered then assignment takes place in the user's workspace (the global environment).

If is , assignment takes place in the initial frame of , unless an existing binding is locked or there is no existing binding and the environment is locked (when an error is signaled).


Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

, , the inverse of , , .


for(i in 1:6) { #-- Create objects 'r.1', 'r.2', ... 'r.6' -- nam <- paste("r", i, sep = ".") assign(nam, 1:i) } ls(pattern = "^r..$") ##-- Global assignment within a function: myf <- function(x) { innerf <- function(x) assign("Global.res", x^2, envir = .GlobalEnv) innerf(x+1) } myf(3) Global.res # 16 a <- 1:4 assign("a[1]", 2) a[1] == 2 # FALSE get("a[1]") == 2 # TRUE

[Package base version 3.5.0 Index]


R’s subsetting operators are powerful and fast. Mastery of subsetting allows you to succinctly express complex operations in a way that few other languages can match. Subsetting is hard to learn because you need to master a number of interrelated concepts:

  • The three subsetting operators.

  • The six types of subsetting.

  • Important differences in behaviour for different objects (e.g., vectors, lists, factors, matrices, and data frames).

  • The use of subsetting in conjunction with assignment.

This chapter helps you master subsetting by starting with the simplest type of subsetting: subsetting an atomic vector with . It then gradually extends your knowledge, first to more complicated data types (like arrays and lists), and then to the other subsetting operators, and . You’ll then learn how subsetting and assignment can be combined to modify parts of an object, and, finally, you’ll see a large number of useful applications.

Subsetting is a natural complement to . shows you the structure of any object, and subsetting allows you to pull out the pieces that you’re interested in.


Take this short quiz to determine if you need to read this chapter. If the answers quickly come to mind, you can comfortably skip this chapter. Check your answers in answers.

  1. What is the result of subsetting a vector with positive integers, negative integers, a logical vector, or a character vector?

  2. What’s the difference between , , and when applied to a list?

  3. When should you use ?

  4. If is a matrix, what does do? How is it different to ?

  5. How can you use a named vector to relabel categorical variables?

  • Data types starts by teaching you about . You’ll start by learning the six types of data that you can use to subset atomic vectors. You’ll then learn how those six data types act when used to subset lists, matrices, data frames, and S3 objects.

  • Subsetting operators expands your knowledge of subsetting operators to include and , focussing on the important principles of simplifying vs. preserving.

  • In Subsetting and assignment you’ll learn the art of subassignment, combining subsetting and assignment to modify parts of an object.

  • Applications leads you through eight important, but not obvious, applications of subsetting to solve problems that you often encounter in a data analysis.

Data types

It’s easiest to learn how subsetting works for atomic vectors, and then how it generalises to higher dimensions and other more complicated objects. We’ll start with , the most commonly used operator. Subsetting operators will cover and , the two other main subsetting operators.

Atomic vectors

Let’s explore the different types of subsetting with a simple vector, .

Note that the number after the decimal point gives the original position in the vector.

There are five things that you can use to subset a vector:

  • Positive integers return elements at the specified positions:

  • Negative integers omit elements at the specified positions:

    You can’t mix positive and negative integers in a single subset:

  • Logical vectors select elements where the corresponding logical value is . This is probably the most useful type of subsetting because you write the expression that creates the logical vector:

    If the logical vector is shorter than the vector being subsetted, it will be recycled to be the same length.

    A missing value in the index always yields a missing value in the output:

  • Nothing returns the original vector. This is not useful for vectors but is very useful for matrices, data frames, and arrays. It can also be useful in conjunction with assignment.

  • Zero returns a zero-length vector. This is not something you usually do on purpose, but it can be helpful for generating test data.

If the vector is named, you can also use:

  • Character vectors to return elements with matching names.


Subsetting a list works in the same way as subsetting an atomic vector. Using will always return a list; and , as described below, let you pull out the components of the list.

Matrices and arrays

You can subset higher-dimensional structures in three ways:

  • With multiple vectors.
  • With a single vector.
  • With a matrix.

The most common way of subsetting matrices (2d) and arrays (>2d) is a simple generalisation of 1d subsetting: you supply a 1d index for each dimension, separated by a comma. Blank subsetting is now useful because it lets you keep all rows or all columns.

By default, will simplify the results to the lowest possible dimensionality. See simplifying vs. preserving to learn how to avoid this.

Because matrices and arrays are implemented as vectors with special attributes, you can subset them with a single vector. In that case, they will behave like a vector. Arrays in R are stored in column-major order:

You can also subset higher-dimensional data structures with an integer matrix (or, if named, a character matrix). Each row in the matrix specifies the location of one value, where each column corresponds to a dimension in the array being subsetted. This means that you use a 2 column matrix to subset a matrix, a 3 column matrix to subset a 3d array, and so on. The result is a vector of values:

Data frames

Data frames possess the characteristics of both lists and matrices: if you subset with a single vector, they behave like lists; if you subset with two vectors, they behave like matrices.

S3 objects

S3 objects are made up of atomic vectors, arrays, and lists, so you can always pull apart an S3 object using the techniques described above and the knowledge you gain from .

S4 objects

There are also two additional subsetting operators that are needed for S4 objects: (equivalent to ), and (equivalent to ). is more restrictive than in that it will return an error if the slot does not exist. These are described in more detail in the OO field guide.


  1. Fix each of the following common data frame subsetting errors:

  2. Why does yield five missing values? (Hint: why is it different from ?)

  3. What does return? How does subsetting a matrix with it work? Do we need any additional subsetting rules to describe its behaviour?

  4. Why does return an error? How does it differ from the similar ?

  5. Implement your own function that extracts the diagonal entries from a matrix (it should behave like where is a matrix).

  6. What does do? How does it work?

Subsetting operators

There are two other subsetting operators: and . is similar to , except it can only return a single value and it allows you to pull pieces out of a list. is a useful shorthand for combined with character subsetting.

You need when working with lists. This is because when is applied to a list it always returns a list: it never gives you the contents of the list. To get the contents, you need :

“If list is a train carrying objects, then is the object in car 5; is a train of cars 4-6.”

— @RLangTip

Because it can return only a single value, you must use with either a single positive integer or a string:

Because data frames are lists of columns, you can use to extract a column from data frames: , .

S3 and S4 objects can override the standard behaviour of and so they behave differently for different types of objects. The key difference is usually how you select between simplifying or preserving behaviours, and what the default is.

Simplifying vs. preserving subsetting

It’s important to understand the distinction between simplifying and preserving subsetting. Simplifying subsets returns the simplest possible data structure that can represent the output, and is useful interactively because it usually gives you what you want. Preserving subsetting keeps the structure of the output the same as the input, and is generally better for programming because the result will always be the same type. Omitting when subsetting matrices and data frames is one of the most common sources of programming errors. (It will work for your test cases, but then someone will pass in a single column data frame and it will fail in an unexpected and unclear way.)

Unfortunately, how you switch between simplifying and preserving differs for different data types, as summarised in the table below.

Data frameoror

Preserving is the same for all data types: you get the same type of output as input. Simplifying behaviour varies slightly between different data types, as described below:

  • Atomic vector: removes names.

  • List: return the object inside the list, not a single element list.

  • Factor: drops any unused levels.

  • Matrix or array: if any of the dimensions has length 1, drops that dimension.

  • Data frame: if output is a single column, returns a vector instead of a data frame.

is a shorthand operator, where is equivalent to . It’s often used to access variables in a data frame, as in or .

One common mistake with is to try and use it when you have the name of a column stored in a variable:

There’s one important difference between and . does partial matching:

If you want to avoid this behaviour you can set the global option to . Use with caution: it may affect behaviour in other code you have loaded (e.g., from a package).

Missing/out of bounds indices

and differ slightly in their behaviour when the index is out of bounds (OOB), for example, when you try to extract the fifth element of a length four vector, or subset a vector with or :

The following table summarises the results of subsetting atomic vectors and lists with and and different types of OOB value.


If the input vector is named, then the names of OOB, missing, or components will be .


  1. Given a linear model, e.g., , extract the residual degrees of freedom. Extract the R squared from the model summary ()

Subsetting and assignment

All subsetting operators can be combined with assignment to modify selected values of the input vector.

Subsetting with nothing can be useful in conjunction with assignment because it will preserve the original object class and structure. Compare the following two expressions. In the first, will remain as a data frame. In the second, will become a list.

With lists, you can use subsetting + assignment + to remove components from a list. To add a literal to a list, use and :


The basic principles described above give rise to a wide variety of useful applications. Some of the most important are described below. Many of these basic techniques are wrapped up into more concise functions (e.g., , , ), but it is useful to understand how they are implemented with basic subsetting. This will allow you to adapt to new situations that are not dealt with by existing functions.

Lookup tables (character subsetting)

Character matching provides a powerful way to make lookup tables. Say you want to convert abbreviations:

If you don’t want names in the result, use to remove them.

Matching and merging by hand (integer subsetting)

You may have a more complicated lookup table which has multiple columns of information. Suppose we have a vector of integer grades, and a table that describes their properties:

We want to duplicate the info table so that we have a row for each value in . We can do this in two ways, either using and integer subsetting, or and character subsetting:

If you have multiple columns to match on, you’ll need to first collapse them to a single column (with , , or ). You can also use or , which do the same thing for you — read the source code to see how.

Random samples/bootstrap (integer subsetting)

You can use integer indices to perform random sampling or bootstrapping of a vector or data frame. generates a vector of indices, then subsetting to access the values:

The arguments of control the number of samples to extract, and whether sampling is performed with or without replacement.

Ordering (integer subsetting)

takes a vector as input and returns an integer vector describing how the subsetted vector should be ordered:

To break ties, you can supply additional variables to , and you can change from ascending to descending order using . By default, any missing values will be put at the end of the vector; however, you can remove them with or put at the front with .

For two or more dimensions, and integer subsetting makes it easy to order either the rows or columns of an object:

More concise, but less flexible, functions are available for sorting vectors, , and data frames, .

Expanding aggregated counts (integer subsetting)

Sometimes you get a data frame where identical rows have been collapsed into one and a count column has been added. and integer subsetting make it easy to uncollapse the data by subsetting with a repeated row index:

Removing columns from data frames (character subsetting)

There are two ways to remove columns from a data frame. You can set individual columns to NULL:

Or you can subset to return only the columns you want:

If you know the columns you don’t want, use set operations to work out which colums to keep:

Selecting rows based on a condition (logical subsetting)

Because it allows you to easily combine conditions from multiple columns, logical subsetting is probably the most commonly used technique for extracting rows out of a data frame.

Remember to use the vector boolean operators and , not the short-circuiting scalar operators and which are more useful inside if statements. Don’t forget De Morgan’s laws, which can be useful to simplify negations:

  • is the same as
  • is the same as

For example, simplifies to , and then to .

is a specialised shorthand function for subsetting data frames, and saves some typing because you don’t need to repeat the name of the data frame. You’ll learn how it works in non-standard evaluation.

Boolean algebra vs. sets (logical & integer subsetting)

It’s useful to be aware of the natural equivalence between set operations (integer subsetting) and boolean algebra (logical subsetting). Using set operations is more effective when:

  • You want to find the first (or last) .

  • You have very few s and very many s; a set representation may be faster and require less storage.

allows you to convert a boolean representation to an integer representation. There’s no reverse operation in base R but we can easily create one:

Let’s create two logical vectors and their integer equivalents and then explore the relationship between boolean and set operations.

When first learning subsetting, a common mistake is to use instead of . Here the achieves nothing: it switches from logical to integer subsetting but the result will be exactly the same. In more general cases, there are two important differences. First, when the logical vector contains NA, logical subsetting replaces these values by NA while drops these values. Second, is not equivalent to : if is all FALSE, will be and is still , so you’ll get no values, instead of all values. In general, avoid switching from logical to integer subsetting unless you want, for example, the first or last value.


  1. How would you randomly permute the columns of a data frame? (This is an important technique in random forests.) Can you simultaneously permute the rows and columns in one step?

  2. How would you select a random sample of rows from a data frame? What if the sample had to be contiguous (i.e., with an initial row, a final row, and every row in between)?

  3. How could you put the columns in a data frame in alphabetical order?


  1. Positive integers select elements at specific positions, negative integers drop elements; logical vectors keep elements at positions corresponding to ; character vectors select elements with matching names.

  2. selects sub-lists. It always returns a list; if you use it with a single positive integer, it returns a list of length one. selects an element within a list. is a convenient shorthand: is equivalent to .

  3. Use if you are subsetting a matrix, array, or data frame and you want to preserve the original dimensions. You should almost always use it when subsetting inside a function.

  4. If is a matrix, will replace every element with 0, keeping the same number of rows and columns. completely replaces the matrix with the value 0.

  5. A named character vector can act as a simple lookup table:

0 thoughts on “R Cran Print Table Assignments”


Leave a Comment

Your email address will not be published. Required fields are marked *