Popular Tutorials

Popular examples, learn python interactively, r introduction.

  • R Reserved Words
  • R Variables and Constants
  • R Operators
  • R Operator Precedence and Associativitys

R Flow Control

  • R if…else Statement
  • R ifelse() Function
  • R while Loop
  • R break and next Statement
  • R repeat loop
  • R Functions
  • R Return Value from Function
  • R Environment and Scope
  • R Recursive Function
  • R Infix Operator
  • R switch() Function

R Data Structures

R Data Frame

R Object & Class

  • R Classes and Objects
  • R Reference Class

R Graphs & Charts

  • R Histograms
  • R Pie Chart
  • R Strip Chart

R Advanced Topics

  • R Plot Function
  • R Multiple Plots
  • Saving a Plot in R
  • R Plot Color

Related Topics

In this article, you will learn to work with lists in R programming. You will learn to create, access, modify and delete list components.

If a vector has elements of different types, it is called a list in R programming.

A list is a flexible data structure that can hold elements of different types, such as numbers, characters, vectors, matrices, and even other lists.

  • How to create a list in R programming?

We can create a list using the list() function.

Here, we create a list x , of three components with data types double , logical and integer vector respectively.

The structure of the above list can be examined with the str() function

In this example, a , b and c are called tags which makes it easier to reference the components of the list.

However, tags are optional. We can create the same list without the tags as follows. In such a scenario, numeric indices are used by default.

  • How to access components of a list?

Lists can be accessed in similar fashion to vectors. Integer, logical or character vectors can be used for indexing. Let us consider a list as follows.

Indexing with [ as shown above will give us a sublist not the content inside the component. To retrieve the content, we need to use [[ .

However, this approach will allow us to access only a single component at a time.

An alternative to [[ , which is used often while accessing content of a list is the $ operator. They are both the same, except that $ can do partial matching on tags.

  • How to modify a list in R?

We can change components of a list through reassignment. We can choose any of the component accessing techniques discussed above to modify it.

Notice below that modification causes reordering of components.

  • How to add components to a list?

Adding new components is easy. We simply assign values using new tags and it will pop into action.

  • How to delete components from a list?

We can delete a component by assigning NULL to it.

Table of Contents

  • Introduction

Sorry about that.

R Tutorials

Programming

6   Lists and data frames

An R list is an object consisting of an ordered collection of objects known as its components .

There is no particular need for the components to be of the same mode or type, and, for example, a list could consist of a numeric vector, a logical value, a matrix, a complex vector, a character array, a function, and so on. Here is a simple example of how to make a list:

Components are always numbered and may always be referred to as such. Thus if Lst is the name of a list with four components, these may be individually referred to as Lst[[1]] , Lst[[2]] , Lst[[3]] and Lst[[4]] . If, further, Lst[[4]] is a vector subscripted array then Lst[[4]][1] is its first entry.

If Lst is a list, then the function length(Lst) gives the number of (top level) components it has.

Components of lists may also be named , and in this case the component may be referred to either by giving the component name as a character string in place of the number in double square brackets, or, more conveniently, by giving an expression of the form

for the same thing.

This is a very useful convention as it makes it easier to get the right component if you forget the number.

So in the simple example given above:

Lst$name is the same as Lst[[1]] and is the string "Fred" ,

Lst$wife is the same as Lst[[2]] and is the string "Mary" ,

Lst$child.ages[1] is the same as Lst[[4]][1] and is the number 4 .

Additionally, one can also use the names of the list components in double square brackets, i.e., Lst[["name"]] is the same as Lst$name . This is especially useful, when the name of the component to be extracted is stored in another variable as in

It is very important to distinguish Lst[[1]] from Lst[1] . [[...]] is the operator used to select a single element, whereas [...] is a general subscripting operator. Thus the former is the first object in the list Lst , and if it is a named list the name is not included. The latter is a sublist of the list Lst consisting of the first entry only. If it is a named list, the names are transferred to the sublist.

The names of components may be abbreviated down to the minimum number of letters needed to identify them uniquely. Thus Lst$coefficients may be minimally specified as Lst$coe and Lst$covariance as Lst$cov .

The vector of names is in fact simply an attribute of the list like any other and may be handled as such. Other structures besides lists may, of course, similarly be given a names attribute also.

6.2 Constructing and modifying lists

New lists may be formed from existing objects by the function list() . An assignment of the form

sets up a list Lst of m components using object_1 , …, object_m for the components and giving them names as specified by the argument names, (which can be freely chosen). If these names are omitted, the components are numbered only. The components used to form the list are copied when forming the new list and the originals are not affected.

Lists, like any subscripted object, can be extended by specifying additional components. For example

6.2.1 Concatenating lists

When the concatenation function c() is given list arguments, the result is an object of mode list also, whose components are those of the argument lists joined together in sequence.

Recall that with vector objects as arguments the concatenation function similarly joined together all arguments into a single vector structure. In this case all other attributes, such as dim attributes, are discarded.

6.3 Data frames

A data frame is a list with class "data.frame" . There are restrictions on lists that may be made into data frames, namely

  • The components must be vectors (numeric, character, or logical), factors, numeric matrices, lists, or other data frames.
  • Matrices, lists, and data frames provide as many variables to the new data frame as they have columns, elements, or variables, respectively.
  • Vector structures appearing as variables of the data frame must all have the same length , and matrix structures must all have the same number of rows .

A data frame may for many purposes be regarded as a matrix with columns possibly of differing modes and attributes. It may be displayed in matrix form, and its rows and columns extracted using matrix indexing conventions.

6.3.1 Making data frames

Objects satisfying the restrictions placed on the columns (components) of a data frame may be used to form one using the function data.frame :

A list whose components conform to the restrictions of a data frame may be coerced into a data frame using the function as.data.frame()

The simplest way to construct a data frame from scratch is to use the read.table() function to read an entire data frame from an external file. This is discussed further in Reading data from files .

6.3.2 attach() and detach()

The $ notation, such as accountants$home , for list components is not always very convenient. A useful facility would be somehow to make the components of a list or data frame temporarily visible as variables under their component name, without the need to quote the list name explicitly each time.

The attach() function takes a ‘database’ such as a list or data frame as its argument. Thus suppose lentils is a data frame with three variables lentils$u , lentils$v , lentils$w . The attach

places the data frame in the search path at position 2, and provided there are no variables u , v or w in position 1, u , v and w are available as variables from the data frame in their own right. At this point an assignment such as

does not replace the component u of the data frame, but rather masks it with another variable u in the workspace at position 1 on the search path. To make a permanent change to the data frame itself, the simplest way is to resort once again to the $ notation:

However the new value of component u is not visible until the data frame is detached and attached again.

To detach a data frame, use the function

More precisely, this statement detaches from the search path the entity currently at position 2. Thus in the present context the variables u , v and w would be no longer visible, except under the list notation as lentils$u and so on. Entities at positions greater than 2 on the search path can be detached by giving their number to detach , but it is much safer to always use a name, for example by detach(lentils) or detach("lentils")

Note: In R lists and data frames can only be attached at position 2 or above, and what is attached is a copy of the original object. You can alter the attached values via assign , but the original list or data frame is unchanged.

6.3.3 Working with data frames

A useful convention that allows you to work with many different problems comfortably together in the same workspace is

  • gather together all variables for any well defined and separate problem in a data frame under a suitably informative name;
  • when working with a problem attach the appropriate data frame at position 2, and use the workspace at level 1 for operational quantities and temporary variables;
  • before leaving a problem, add any variables you wish to keep for future reference to the data frame using the $ form of assignment, and then detach() ;
  • finally remove all unwanted variables from the workspace and keep it as clean of left-over temporary variables as possible.

In this way it is quite simple to work with many problems in the same directory, all of which have variables named x , y and z , for example.

6.3.4 Attaching arbitrary lists

attach() is a generic function that allows not only directories and data frames to be attached to the search path, but other classes of object as well. In particular any object of mode "list" may be attached in the same way:

Anything that has been attached can be detached by detach , by position number or, preferably, by name.

6.3.5 Managing the search path

The function search shows the current search path and so is a very useful way to keep track of which data frames and lists (and packages) have been attached and detached. Initially it gives

where .GlobalEnv is the workspace. 1

1  See the on-line help for autoload for the meaning of the second term.

After lentils is attached we have

and as we see ls (or objects ) can be used to examine the contents of any position on the search path.

Finally, we detach the data frame and confirm it has been removed from the search path.

Introduction

  • R installation
  • Working directory
  • Getting help
  • Install packages

Data structures

Data Wrangling

  • Sort and order
  • Merge data frames

Programming

  • Creating functions
  • If else statement
  • apply function
  • sapply function
  • tapply function

Import & export

  • Read TXT files
  • Import CSV files
  • Read Excel files
  • Read SQL databases
  • Export data
  • plot function
  • Scatter plot
  • Density plot
  • Tutorials Introduction Data wrangling Graphics Statistics See all

Create lists in R to store any type of R objects

What is a list in R? A list in R programming language is an ordered collection of any R objects . Thus, although the elements of vectors, matrix and arrays must be of the same type, in the case of the R list the elements can be of different type . Therefore, you can mix several data types with this structure.

Create a list in R

If you don’t know how to create a list in R , you just need to use the list function as follows, specifying the objects you want to join inside your list.

Naming lists in R

As other R data structures, you can name your list element objects in order to identify or having an easier access to the elements. The following block of code shows how to create a named list in R.

Extract elements from list in R

Now, we are going to index the list elements in order to access the data we want. For that purpose, you can extract the list elements with single or double brackets .

However, in case you have named your list elements you can use the previous way to get values, specify the names of the elements of the list you want to access inside brackets, or use the $ operator as in the following examples:

If you use double square brackets instead of single square brackets for subsetting a list, the output class will be simplified as much as possible.

Length of a list in R

The length of a list is the number of R objects inside the list . With this in mind, you can obtain the number of list elements with the length function. However, if you want to know the length of any object inside the list, first you will need to extract the corresponding element.

Create empty list in R

Sometimes you need to fill a list inside a for loop . For that purpose, it is interesting to create an empty list in R . Although you can create an empty list with the list function, if you want a prespecified length you need to use the vector function and specify the final length in the length argument to create a list of length n .

So if you want to fill this list within a for loop, you could do as follows:

Append to list in R

If you need to add an element to a list , you can specify the object you want to add at the next index of the length of the list. If the list length is 3, you can add the new object to the fourth slot.

Now, print your new list and you will have the following output:

Remove element from list in R

In order to delete some elements from a list you can set the index of the element of the list you want to remove as NULL , or indicate inside brackets the index with the - operator. If you want to remove several elements at once, combine them with the c function.

Creating a list of lists

You can also nest lists in R . This means that in all or some elements of your root list you will have a list. That list can also store other lists or other types of objects. You can achieve this with the list function, adding new lists as list elements. In this example we are going to add our two previously created lists inside a new list.

Printing the nested list will result into the following:

Accessing list of list elements

Accessing elements of lists inside lists is similar to access the elements to one list . In fact, if you access one list and store it inside an object, the process is the same as presented in the single-list element extraction section. If not, you will have to know and follow the level of hierarchy of the list . You have some examples in the following code block:

Combine lists in R

Two or more R lists can be joined together. For that purpose, you can use the append , the c or the do.call functions. When combining the lists this way, the second list elements will be appended at the end of the first list .

Merge list with same names

When you have two or more lists with the same element names , you can merge the list elements withing a list of the same length as the previous ones, where the elements with the same name will be concatenated. First, we are going to copy our named list in other variable:

Now, you can use the Map or the mapply functions with those lists the following way.

You can see the output of the list with concatenated elements:

Note that the element C is no longer a matrix .

Compare two lists in R

You can compare two lists in different ways. This include obtaining the common elements, the different elements or comparing the equal ones. Before each explanation we are going to copy our first list and change its first element.

Common elements in two R lists

First, if you want to obtain the same elements in two lists you can use the intersect function, that will return a list with the common elements of the lists.

Different elements in two R lists

Second, with the setdiff function you will obtain the different items between your lists . Note that the order you pass the lists is important .

Compare equal elements in two R lists

Third, you can also compare the equal items of two lists with %in% operator or with the compare.list function of the useful library. The result will be a logical vector.

List to vector

Sometimes you need to convert your list to other object types. The most common conversion is converting a list to vector . For that purpose, you can use the unlist function.

If you prefer to convert the full list to vector, set the use.names to FALSE .

Note that in this case all the elements are now a characters.

In addition, the purrr library have some functions similar to the unlist function but in this case you can specify the output class . In this example we are converting our new list to double and then to character.

List to dataframe

Suppose you have a list containing data of some variables. In that case, you may want to convert your list to a data frame. In order to achieve it, you can use the unlist , matrix and data.frame functions or the do.call function as follows.

If you are working with characters, set stringsAsFactors = FALSE to avoid character columns converted to factor.

R PACKAGES IO

Explore and discover thousands of packages, functions and datasets

R CHARTS

Learn how to plot your data in R with the base package and ggplot2

PYTHON CHARTS

PYTHON CHARTS

Learn how to create plots in Python with matplotlib, seaborn, plotly and folium

Related content

Factor in R

Factor in R

Introduction to R

Learn how to deal with a FACTOR in R ✅ CREATE factors, CHANGE LABELS, RELEVEL, ORDER, REORDER the levels and CONVERT the factors to other data types

Data frame in R

Data frame in R

DATA FRAME in R programming ⚡ With this tutorial you will learn how to CREATE and ACCESS a DATAFRAME in R, ADD or REMOVE columns and rows, SORT and FILTER

Matrix in R

Matrix in R

Matrix in R language WITH EXAMPLES ✅ CREATE a matrix, ADD and DELETE columns and rows, add and remove names, stack matrices and remove NA, NaN and Inf

Try adjusting your search query

👉 If you haven’t found what you’re looking for, consider clicking the checkbox to activate the extended search on R CHARTS for additional graphs tutorials, try searching a synonym of your query if possible (e.g., ‘bar plot’ -> ‘bar chart’), search for a more generic query or if you are searching for a specific function activate the functions search or use the functions search bar .

Introduction to Programming with R

Chapter 9 lists.

In terms of ‘data types’ (objects containing data) we have only been working with atomic vectors and matrices which are both homogenous objects – they can always only contain data of one specific type.

As we will learn, data frames are typically lists of atomic vectors of the same length.

Figure 9.1: As we will learn, data frames are typically lists of atomic vectors of the same length.

In this chapter we will learn about lists and data frames which allow to store heterogenous data, e.g., integers and characters both in the same object. This chapter does not cover all details of lists, but we will learn all the important aspects we need in the next chapter when learning about data frames as data frames are based on lists (similar to matrices being based on vectors).

Quick reminder: Frequently used data types and how they can be distinguished by their dimensionality and whether they are homogeneous (all elements of the same type) vs. heterogeneous (elements can be of different types).

Dimension Homogenous Heterogenous
1 Atomic vectors Lists
2 Matrix Data frame
\(\ge 1\) Array

9.1 List introduction

As ( atomic ) vectors , lists are also sequences of elements . However, in contrast to (atomic) vectors, lists allow for heterogenity. Technically a list is a generic vector but often only called ‘ list ’. We will use the same term in this book (atomic vectors: vectors; generic vectors: lists).

Basis : Lists serve as the basis for most complex objects in R .

  • Data frames : Lists of variables of the same length, often (but not necessarily) atomic vectors.
  • Fitted regression models : Lists of different elements such as the model parameters, covariance matrix, residuals, but also more technical information such as the regression terms or certain matrix decompositions.

Difference : The difference between vectors and lists.

  • Vector : All elements must have the same basic type.
  • List : Different elements can have different types, including vectors, matrices, lists or more complex objects.

As lists are ‘generic vectors’, empty lists can also be created using the vector() function (compare Creating vectors ).

Elements of (unnamed) lists are indexed by [[...]] , while we had [...] for vectors. The empty list above has two elements where both (first [[1]] and second [[2]] ) both contain NULL .

9.2 Creating lists

We start right away with constructing a few simple lists for illustration. While vectors can be created using c() , lists are most often constructed using the function list() .

A vector : Vector of length 2.

A list : List containing values of the same types/classes.

This list with two elements ( [[1]] , [[2]] ) contains two vectors, each of length one, indicated by [1] (first vector element).

Another list : Store objects of different types/classes into a list.

The last example shows a list of length 3 which contains a numeric vector of length \(1\) (first element; [[1]] ), a character vector of length \(2\) (second element; [[2]] ), and a matrix of dimension \(2 \times 3\) (third element; [[3]] ).

The two functions c() and list() work very similarly, except that c(a, b) where a and b are vectors performs coercion to convert all values into one specific type (see Vectors: Coercion ).

9.3 Recursive structure

A more practical example : We have some information about Peter Falk , a famous actor who played “Lieutenant Columbo” in the long-running TV series Columbo between 1968–2003.

We would like to store all the information in one single object. As we have to deal with both characters (name; month of birth) and numeric values (year and day of birth), we need an object which allows for heterogenity – a list.

For named lists, the representation (print) changes again compared to unnamed lists. The elements are now indicated by e.g., $name or $date_of_birth$year which we can use to access specific elements. We will come back later when Subsetting lists .

Our new object person is a list which contains a named vector ( $name ) and a second element ( $date_of_birth ) which itself contains another named list. This is called a recursive structure , a list can contain lists (can contain lists (can …)). The figure below shows the structure of the object person with the two lists in green, and the different (integer/character) vectors in blue.

Graphical representation of the recursive list object `person`.

Figure 9.2: Graphical representation of the recursive list object person .

A nice way to get an overview of potentially complex (list-)objects is by using the function str() (structure) which we have already seen in the vectors chapter. str() returns us a text-representation similar to the image shown above.

How to read : the (first-level) list has two elements, one called name , one date_of_birth . The name element itself contains a named character of length \(2\) , the second element date_of_birth is again a list with \(3\) named elements ( year , month , day ) containing unnamed (plain) vectors of length \(1\) (numeric, character, numeric). The indent shows the recursive structure, the more to the right of the $ , the deeper a specific entry in the list.

9.4 List attributes

As all other objects lists always have a specific type and length (object properties). Besides these mandatory properties the default attributes for lists are:

  • Class : Objects of class "list" .
  • Names : Can have names (optional; just like vectors).

Let us investigate the person object from above:

The is.*() function family can be used to check the object.

  • is.list() : Always returns TRUE for lists.
  • is.vector() : As lists are generic vectors they also count as vectors, as long as they only have class, length, type and names (optional).
  • A list is never numeric, integer, character, or logical, no matter what the list contains.

9.5 Subsetting lists

Subsetting on lists works slightly different than on vectors and matrices. The basic concepts stay the same, however, due to the more complex structure of the object, additional operators for subsetting become available.

Operator Return Description
Select sub-list containing one or more elements. The index vector can be integer (possibly negative), character, or logical.
Select the of a single list element if is a single (positive) integer or a single character.
Select the of a single list element using the name of the element (without quotes).
If is a vector, nested/recursive subsetting takes place.

Note that there is a distinct difference between single brackets ( [...] ) and double brackets ( [[...]] ). The first always returns a list which is a subset of the original object to be subsetted, while the latter returns the content of these elements.

Using [i] : The method is similar to vector subsetting except that the result will not be the content of the elements specified, but a sub-list. Let us call persons[1] and see what we get:

The result of person[1] is again a list, but only contains the first entry of the original object person . In the same way we can use person["name"] or person[c(TRUE, FALSE)] . This also works with vectors, e.g., extracting elements 2:1 (both but reverse order):

A negative index ( person[-1] ) can be used to get all but the first element (does not work with characters). The result is again a sub-list (like for positive indices).

Using [[i]] , single value : This subsetting type is most comparable to vector subsetting. Instead of a sub-list, we will get the content of the element, in this case a named character vector of length \(2\) .

The same can be achieved using person[["name"]] on named lists. Note that subsetting with negative indices ( person[[-1]] ) does not work in combination with double brackets.

Using the $ operator : Most commonly used when working with named lists is the $ operator. This operator is called the dollar operator . Instead of calling person[["name"]] we can also call person$name as long as the name does not contain blanks or special characters. Note that there is no blank before/after the $ operator (not as shown in the output of str() ).

Multiple $ operators can also be combined. If we are interested in the month of birth ( month ) which is stored within date_of_birth we can use:

How to read :

  • Right to left : Return month from date_of_birth of the object person .
  • Left to right : Inside object person access the element date_of_birth , inside date_of_birth access element month .

Using [[j]] with vectors : Take care, something unexpected happens. As an example, let us call person[[c(1, 2)]] . We could think this returns us person[[1]] and person[[2]] , but that’s not the case. Instead, nested or recursive subsetting is performed. The two indices ( c(1, 2) ) are used as indices for different depths of the recursive list.

What happened: The first element of the vector (here 1 ) is used for the top-level list. Our first entry the vector name . The second element of the vector ( 2 ) is then used to extract the second element of whatever name contains. It is the same as:

Note : We will not use this often, but keep it in mind if you run into interesting results when subsetting lists or data frames. The same happens if you use a vector, e.g., person[[c("name", "last_name")]] or person[[c("date_of_birth", "month")]] .

Exercise 9.1 Practicing subsetting on lists : The following object demo is a list with information about two persons, Frank and Petra (simply copy&paste it into your R session).

  • How do we get Franks location?
  • Try demo["Frank"]$location (will return NULL ). Why doesn’t this work?
  • How many kids does Frank have (use code to answer)?
  • Our friend Petra moves from Birmingham to Vienna. Change her location (inside demo ) to Vienna.

Solution . Franks location : demo is a list with two elements, one called "Frank" . Thus, we can access the first list element using demo$Frank . This returns the content of this list element which itself is, again, a list. In there, we have the location we are looking for.

Thus, one option to get Franks location is to use:

Alternatively, we could use brackets and subsetting by name. Warning: we need double brackets to access the content .

Try demo["Frank"]$location : This will not work. The reason is that we only use single brackets!

demo["Frank"] returns a sub-list of demo which now only contains "Frank" (no longer "Petra" ). However, we do not get the content or information for Frank. Let see:

The last line looks werid but always only just extract "Frank" from itself but does not access the list element for "Frank" . Thus, when we try to access location (which does not exist on this level) we get a NULL in return.

How many kids does Frank have? To answer this question, we need to find out how long the kids vector is. Again, we can access this specific element in different ways, the most easy one:

Petra moves to Vienna : You can use any subsetting technique and assign a new value. I will stick to the $ operator and do the following:

9.6 Replacing/deleting elements

Replacement functions are available for all subset types above which can be used to overwrite elements in an existing list or add new elements to a list.

As an example, let us replace the element $name in the person object. We use subsetting with the $ operator and assign (store) a new object. As person$name exists, it will be replaced.

Or replace the month in the date of birth with an integer 9L instead of "September" :

The same way, new elements can be added. If the element we assign an object to does not yet exist, it will be added to the original list object. Let us add a job element containing "Actor" :

Delete elements : To delete an element, we simply have to replace it with a NULL object. An example using a very simple list:

As you can see it is possible that a list element can contain NULL (see element c ) but if assigned ( x$a <- NULL ) R will remove the element completely (not storing NULL on it).

Exercise 9.2 Practicing replacement : As in the previous exercise we will use the following list to work with. The list contains information about Petra and Frank.

We need to update this list and add or change some of the elements.

  • Petra moves from Birmingham to Vienna. Update her location.
  • Frank just got a newborn baby called "Malena" . Add her name to the kids vector.
  • Add a third person called ‘Regina’, located in ‘Sydney’. She has one child called ‘Lea’ and works as a ‘Teacher’.

Solution . Petra moves to Vienna : You can use any subsetting methods we have just seen. In this solution we will stick to the $ operator. All we have to do is to access Petras location, and assign a new value.

Frank got a third child : Here, we could do the same as for Petra and simply assign a new vector with all three kids to Frank ( demo$Frank$kids <- c("Peter", "Paul", "Malena") ). However, this is not super nice (hard-coded).

Instead we use c() and combine the vector containing the first two kids with the new born, and store the vector (combination of subsetting and replacement) as follows:

Adding Regina : Regina is not yet in our list, however, we can assign new elements the same way we replace elements. If the element exists it will be overwritten. If it does not exist, it will be added. In this case we want to add a new list to the existing object demo called $Regina :

9.7 Combining lists

Multiple lists can be combined using either c() or list() .

  • c(<list 1>, <list 2>) : Creates a new list by combining all elements from the two lists. The result is a list with a length of the number of elements from <list 1> and <list 2> combined.
  • list(<list 1>, <list 2>) : Creates a new list of length 2 , where the first element contains <list 1> , the second <list 2> .

Example: Using two lists list1 and list2 (both of length 2).

The latter results in a recursive list where each element from the list res2 itself contains a list with two elements. As shown, we can also name the elements (similar to cbind() / rbind() when creating matrices; Matrices: Combining objects ). Note that the naming of the list-elements has a different effect when using c() (try c(list_one = list1, list_two = list2) ).

9.8 Summary

Just as a brief summary to recap the new content:

  • Creating lists : Using the function list() .
  • Name attribute : Lists can be named or unnamed.
  • Heterogenity : Allows to store objects of different types.
  • Replacement : Subsetting can be used to replace existing elements, add new elements, or delete elemets (assigning NULL ).
  • Recursive lists : Lists can be recursive (lists containing lists containing lists …).

An overview of the different subsetting methods we have learned for different objects (vectors, matrices, and lists).

Subset By index By name Logical
Element [possible]
Element or [possible]
Row [possible]
Column [possible]
List [possible]
Element or [not possible]
Element (recursive) [not possible]

Most subsetting methods also work with vectors (vectors of indices or names). You will see that we can re-use most of this when working with data frames, our next topic.

What is a List?

Vectors and matrices are incredibly useful data structure in R, but they have one distinct limitation: they can store only one type of data.

Lists, however, can store multiple types of values at once. A list can contain a numeric matrix, a logical vector, a character string, a factor object and even another list.

Create a List

Creating a list is much like creating a vector; just pass a comma-separated sequence of elements to the list() function.

The best way to understand the contents of a list is to use the structure function str() . It provides a compact display of the internal structure of a list.

Nested List

A list can contain sublists, which in turn can contain sublists themselves, and so on. This is known as nested list or recursive vectors.

Subsetting List by Position

There are two ways to extract elements from a list:

  • Using [[]] gives you the element itself.
  • Using [] gives you a list with the selected elements.

You can use [] to extract either a single element or multiple elements from a list. However, the result will always be a list.

You can use [[]] to extract only a single element from a list. Unlike [] , [[]] gives you the element itself.

You can’t use logical vectors or negative numbers as indices when using [[]]

Difference Between Single Bracket [] and Double Bracket [[]]

The difference between [] and [[]] is really important for lists, because [[]] returns the element itself while [] returns a list with the selected elements.

The difference becomes clear when we inspect the structure of the output – one is a character and the other one is a list.

The difference becomes annoyingly obvious when we cat the value. As you know cat() can print any value except the structured object.

Subsetting List by Names

Each list element can have a name. You can access individual element by specifying its name in double square brackets [[]] or use $ operator.

$ works similarly to [[]] except that you don’t need to use quotes.

Subsetting Nested List

You can access individual items in a nested list by using the combination of [[]] or $ operator and the [] operator.

Modify List Elements

Modifying a list element is pretty straightforward. You use either the [[]] or the $ to access that element, and simply assign a new value.

You can modify components using [] as well, but you have to assign a list of components.

Using [] allows you to modify more than one component at once.

Add Elements to a List

You can use same method for modifying elements and adding new one. If the element is already present in the list, it is updated else, a new element is added to the list.

By using append() method you can append one or more elements to the list.

Remove an Element from a List

To remove a list element, select it by position or by name, and then assign NULL to it.

Using [] , you can delete more than one component at once.

By using a logical vector, you can remove list elements based on the condition.

Combine Lists

The c() does a lot more than just creating vectors. It can be used to combine lists into a new list as well.

Flatten a List into a Vector

Basic statistical functions work on vectors but not on lists.

For example, you cannot directly compute the mean of list of numbers. In that case, you have to flatten the list into a vector using unlist() first and then compute the mean of the result.

Find List Length

To find the length of a list, use length() function.

list assignment in r

Secure Your Spot in Our Statistical Methods in R Online Course Starting on September 9 (Click for More Info)

Joachim Schork Image Course

Assignment Operators in R (3 Examples) | Comparing = vs. <- vs. <<-

On this page you’ll learn how to apply the different assignment operators in the R programming language .

The content of the article is structured as follows:

Let’s dive right into the exemplifying R syntax!

Example 1: Why You Should Use <- Instead of = in R

Generally speaking, there is a preference in the R programming community to use an arrow (i.e. <-) instead of an equal sign (i.e. =) for assignment.

In my opinion, it makes a lot of sense to stick to this convention to produce scripts that are easy to read for other R programmers.

However, you should also take care about the spacing when assigning in R. False spacing can even lead to error messages .

For instance, the following R code checks whether x is smaller than minus five due to the false blank between < and -:

A properly working assignment could look as follows:

However, this code is hard to read, since the missing space makes it difficult to differentiate between the different symbols and numbers.

In my opinion, the best way to assign in R is to put a blank before and after the assignment arrow:

As mentioned before, the difference between <- and = is mainly due to programming style . However, the following R code using an equal sign would also work:

In the following example, I’ll show a situation where <- and = do not lead to the same result. So keep on reading!

Example 2: When <- is Really Different Compared to =

In this Example, I’ll illustrate some substantial differences between assignment arrows and equal signs.

Let’s assume that we want to compute the mean of a vector ranging from 1 to 5. Then, we could use the following R code:

However, if we want to have a look at the vector x that we have used within the mean function, we get an error message:

Let’s compare this to exactly the same R code but with assignment arrow instead of an equal sign:

The output of the mean function is the same. However, the assignment arrow also stored the values in a new data object x:

This example shows a meaningful difference between = and <-. While the equal sign doesn’t store the used values outside of a function, the assignment arrow saves them in a new data object that can be used outside the function.

Example 3: The Difference Between <- and <<-

So far, we have only compared <- and =. However, there is another assignment method we have to discuss: The double assignment arrow <<- (also called scoping assignment).

The following code illustrates the difference between <- and <<- in R. This difference mainly gets visible when applying user-defined functions .

Let’s manually create a function that contains a single assignment arrow:

Now, let’s apply this function in R:

The data object x_fun1, to which we have assigned the value 5 within the function, does not exist:

Let’s do the same with a double assignment arrow:

Let’s apply the function:

And now let’s return the data object x_fun2:

As you can see based on the previous output of the RStudio console, the assignment via <<- saved the data object in the global environment outside of the user-defined function.

Video & Further Resources

I have recently released a video on my YouTube channel , which explains the R syntax of this tutorial. You can find the video below:

The YouTube video will be added soon.

In addition to the video, I can recommend to have a look at the other articles on this website.

  • R Programming Examples

In summary: You learned on this page how to use assignment operators in the R programming language. If you have further questions, please let me know in the comments.

assignment-operators-in-r How to use different assignment operators in R – 3 R programming examples – R programming language tutorial – Actionable R programming syntax in RStudio

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe. I hate spam & you may opt out anytime: Privacy Policy .

Leave a Reply Cancel reply

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

Post Comment

Joachim Schork Statistician Programmer

I’m Joachim Schork. On this website, I provide statistics tutorials as well as code in Python and R programming.

Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe. I hate spam & you may opt out anytime: Privacy Policy .

Statistical Methods Announcement

Related Tutorials

Number of Months Between Two Dates in R (Example)

Number of Months Between Two Dates in R (Example)

Get Row Index Number in R (Example) | Find Indices in Data Frame

Get Row Index Number in R (Example) | Find Indices in Data Frame

  • Data Visualization
  • Statistics in R
  • Machine Learning in R
  • Data Science in R
  • Packages in R

R – Lists

A list in R programming is a generic object consisting of an ordered collection of objects. Lists are one-dimensional , heterogeneous data structures.

The list can be a list of vectors , a list of matrices, a list of characters, a list of functions , and so on. 

A list is a vector but with heterogeneous data elements. A list in R is created with the use of the list() function .

R allows accessing elements of an R list with the use of the index value. In R, the indexing of a list starts with 1 instead of 0.

Creating a List

To create a List in R you need to use the function called “ list() “.

In other words, a list is a generic vector containing other objects. To illustrate how a list looks, we take an example here. We want to build a list of employees with the details. So for this, we want attributes such as ID, employee name, and the number of employees. 

Example:   

         

Naming List Components

Naming list components make it easier to access them.

Accessing R List Components

We can access components of an R list in two ways. 

1. Access components by names:

All the components of a list can be named and we can use those names to access the components of the R list using the dollar command.

Example:  

2. Access components by indices:

We can also access the components of the R list using indices.

To access the top-level components of a R list we have to use a double slicing operator “ [[ ]] ” which is two square brackets and if we want to access the lower or inner-level components of a R list we have to use another square bracket “ [ ] ” along with the double slicing operator “ [[ ]] “.

Modifying Components of a List

A R list can also be modified by accessing the components and replacing them with the ones which you want.

Concatenation of lists

Two R lists can be concatenated using the concatenation function. So, when we want to concatenate two lists we have to use the concatenation operator.

Syntax:   

list = c(list, list1) list = the original list  list1 = the new list 

Adding Item to List

To add an item to the end of list, we can use append() function.

Deleting Components of a List

To delete components of a R list, first of all, we need to access those components and then insert a negative sign before those components. It indicates that we had to delete that component. 

Merging list

We can merge the R list by placing all the lists into a single list.

Converting List to Vector

Here we are going to convert the R list to vector, for this we will create a list first and then unlist the list into the vector.

R List to matrix

We will create matrices using matrix() function in R programming. Another function that will be used is unlist() function to convert the lists into a vector.

In this article we have covered Lists in R, we have covered list operations like creating, naming, merging and deleting a list in R language. R list is an important concept and should not be skipped.

Hope you learnt about R lists and it’s operations in this article.

Also Check:

  • R – Matrices

Please Login to comment...

Similar reads.

  • Write From Home
  • How to Get a Free SSL Certificate
  • Best SSL Certificates Provider in India
  • Elon Musk's xAI releases Grok-2 AI assistant
  • What is OpenAI SearchGPT? How it works and How to Get it?
  • Full Stack Developer Roadmap [2024 Updated]

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Popular Tutorials

Popular examples, learn python interactively, r introduction.

  • R Getting Started
  • R Variables and Constants
  • R Data Types
  • R Print Output

R Flow Control

  • R Boolean Expression
  • R if...else
  • R ifelse() Function
  • R while Loop
  • R break and next
  • R repeat Loop

R Data Structure

  • R Data Frame

R Data Visualization

  • R Histogram
  • R Pie Chart

R Strip Chart

  • R Plot Function
  • R Save Plot
  • Colors in R

R Data Manipulation

  • R Read and Write CSV
  • R Read and Write xlsx
  • R min() and max()
  • R mean, median and mode
  • R Percentile

R Additional Topics

  • R Objects and Classes

R Tutorials

  • R Return Value from Function

A List is a collection of similar or different types of data.

In R, we use the list() function to create a list. For example,

  • list1 - list of integers
  • list2 - list containing string, integer, and boolean value
  • Access List Elements in R

In R, each element in a list is associated with a number. The number is known as a list index.

We can access elements of a list using the index number (1, 2, 3 …) . For example,

In the above example, we have created a list named list1 .

Here, we have used the vector index to access the vector elements

  • list1[1] - access the first element 24
  • list1[4] - accesses the third element "Nepal"

Note : In R, the list index always starts with 1 . Hence, the first element of a list is present at index 1 , second element at index 2 and so on.

  • Modify a List Element in R

To change a list element, we can simply reassign a new value to the specific index. For example,

Here, we have reassigned a new value to index 2 to change the list element from "Sabby" to "Cathy" .

  • Add Items to R List

We use the append() function to add an item at the end of the list. For example,

In the above example, we have created a list named list1 . Notice the line,

Here, append() adds 3.14 at the end of the list.

  • Remove Items From a List in R

R allows us to remove items for a list. We first access elements using a list index and add negative sign - to indicate we want to delete the item. For example,

  • [-1] - removes 1st item
  • [-2] - removes 2nd item and so on.

Here, list[-4] removes the 4th item of list1 .

  • Length of R List

In R, we can use the length() function to find the number of elements present inside the list. For example,

Here, we have used the length() function to find the length of list1 . Since there are 4 elements in list1 so length() returns 4 .

  • Loop Over a List

In R, we can also loop through each element of the list using the for loop . For example,

  • Check if Element Exists in R List

In R, we use the %in% operator to check if the specified element is present in the list or not and returns a boolean value.

  • TRUE - if specified element is present in the list
  • FALSE - if specified element is not present in the list

For example,

  • "Larry" is present in list1 , so the method returns TRUE
  • "Kinsley" is not present in list1 , so the method returns FALSE

Table of Contents

  • Introduction

Sorry about that.

Our premium learning platform, created with over a decade of experience and thousands of feedbacks .

Learn and improve your coding skills like never before.

  • Interactive Courses
  • Certificates
  • 2000+ Challenges

Related Tutorials

Programming

list: Lists -- Generic and Dotted Pairs

Description.

Functions to construct, coerce and check for both kinds of R lists.

as.list(x, …) # S3 method for environment as.list(x, all.names = FALSE, sorted = FALSE, …) as.pairlist(x)

is.list(x) is.pairlist(x)

alist(…)

objects, possibly named.

object to be coerced or tested.

a logical indicating whether to copy all values or (default) only those whose names do not begin with a dot.

a logical indicating whether the names of the resulting list should be sorted (increasingly). Note that this is somewhat costly, but may be useful for comparison of environments.

Almost all lists in R internally are Generic Vectors , whereas traditional dotted pair lists (as in LISP) remain available but rarely seen by users (except as formals of functions).

The arguments to list or pairlist are of the form value or tag = value . The functions return a list or dotted pair list composed of its arguments with each value either tagged or untagged, depending on how the argument was specified.

alist handles its arguments as if they described function arguments. So the values are not evaluated, and tagged arguments with no value are allowed whereas list simply ignores them. alist is most often used in conjunction with formals .

as.list attempts to coerce its argument to a list. For functions, this returns the concatenation of the list of formal arguments and the function body. For expressions, the list of constituent elements is returned. as.list is generic, and as the default method calls as.vector (mode = "list") for a non-list, methods for as.vector may be invoked. as.list turns a factor into a list of one-element factors. Attributes may be dropped unless the argument already is a list or expression. (This is inconsistent with functions such as as.character which always drop attributes, and is for efficiency since lists can be expensive to copy.)

is.list returns TRUE if and only if its argument is a list or a pairlist of length \(> 0\). is.pairlist returns TRUE if and only if the argument is a pairlist or NULL (see below).

The " environment " method for as.list copies the name-value pairs (for names not beginning with a dot) from an environment to a named list. The user can request that all named objects are copied. Unless sorted = TRUE , the list is in no particular order (the order depends on the order of creation of objects and whether the environment is hashed). No enclosing environments are searched. (Objects copied are duplicated so this can be an expensive operation.) Note that there is an inverse operation, the as.environment () method for list objects.

An empty pairlist, pairlist() is the same as NULL . This is different from list() : some but not all operations will promote an empty pairlist to an empty list.

as.pairlist is implemented as as.vector (x, "pairlist") , and hence will dispatch methods for the generic function as.vector . Lists are copied element-by-element into a pairlist and the names of the list used as tags for the pairlist: the return value for other types of argument is undocumented.

list , is.list and is.pairlist are primitive functions.

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

vector ("list", length) for creation of a list with empty components; c , for concatenation; formals . unlist is an approximate inverse to as.list() .

‘ plotmath ’ for the use of list in plot annotation.

Run the code above in your browser using DataLab

R Data Structures

R statistics.

A list in R can contain many different data types inside it. A list is a collection of data which is ordered and changeable.

To create a list, use the list() function:

Access Lists

You can access the list items by referring to its index number, inside brackets. The first item has index 1, the second item has index 2, and so on:

Change Item Value

To change the value of a specific item, refer to the index number:

List Length

To find out how many items a list has, use the length() function:

Advertisement

Check if Item Exists

To find out if a specified item is present in a list, use the %in% operator:

Check if "apple" is present in the list:

Add List Items

To add an item to the end of the list, use the append() function:

Add "orange" to the list:

To add an item to the right of a specified index, add " after= index number " in the append() function:

Add "orange" to the list after "banana" (index 2):

Remove List Items

You can also remove list items. The following example creates a new, updated list without an "apple" item:

Remove "apple" from the list:

Range of Indexes

You can specify a range of indexes by specifying where to start and where to end the range, by using the : operator:

Note: When specifying a range, the return value will be a new list with the specified items.

Return the second, third, fourth and fifth item:

Note: The search will start at index 2 (included) and end at index 5 (included).

Remember that the first item has index 1.

Loop Through a List

You can loop through the list items by using a for loop:

Print all items in the list, one by one:

Join Two Lists

There are several ways to join, or concatenate, two or more lists in R.

The most common way is to use the c() function, which combines two elements together:

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

%<<-% {dub}R Documentation

Assign nested components of a list to names

Description.

The %<<-% operator assigns multiple (nested) components of a list or vector to names via pattern matching (“unpacking assignment”). Think of the “dub(ble) arrow” <<- as a pictograph representing multiple <- 's.

%<<-% is especially convenient for:

assigning individual names to the multiple values that a function may return in the form of a list;

extracting deeply nested list components.

Pattern of names that the components of are assigned to (see below).

List or vector.

Returns value invisibly.

Pattern-matching names

Names are matched to the (nested) components of a list using a concise pattern matching syntax that mirrors the structure of the list. Apart from names, the syntax consists of two classes of symbols:

List constructors — Use a pair of parentheses to indicate a list, and a colon, rather than a comma, to indicate successive names.

Wildcards — Use a dot ( . ) to skip assignment of a specific component, or dots ( ... ) to skip assignment of a range of components.

See the examples for an illustration of common use cases.

Unpacking/multiple assignment appears in other languages (e.g., Python , JavaScript , Clojure ). While R has no such feature, using a custom operator to do this has long been a folklore method. An early implementation is due to Gabor Grothendieck (2004), cf. list in the gsubfn package.

  • Nationals Promote Dylan Crews
  • Cardinals Place Willson Contreras On 15-Day IL Due To Finger Fracture
  • Giants, Matt Chapman Have “Had Conversations” About Potential Extension
  • Mariners Hire Edgar Martinez As Hitting Coach For Rest Of 2024
  • Padres Reinstate Yu Darvish From Restricted List
  • Mariners Fire Scott Servais, Hire Dan Wilson As Manager
  • Hoops Rumors
  • Pro Football Rumors
  • Pro Hockey Rumors

MLB Trade Rumors

Astros Shut Down Penn Murfee’s Rehab Assignment

By Darragh McDonald | August 23, 2024 at 12:00pm CDT

Right-hander Penn Murfee began a rehab assignment last week but made just one appearance and will now be shut down. Per Matt Kawahara of the Houston Chronicle , the righty has been returned from that rehab assignment due to what the team calls “a reoccurrence of right elbow discomfort.”

Murfee, now 30, got out to a strong start in his major league career. He made 80 appearances for the Mariners over the 2022 and 2023 seasons with a 2.70 earned run average. He posted a strong 27.9% strikeout rate in that time, with his 8.5% walk rate close to league average.

The latter of those two seasons was cut short midway through, as he underwent Tommy John surgery in July of last year. In the offseason, the M’s put him on waivers and he was claimed by the Mets and then Atlanta. The latter club non-tendered him, re-signed him to a split deal and then put him back on waivers, at which point the Astros claimed him.

Houston was undoubtedly hoping Murfee could provide a second-half jolt to their bullpen once he recovered from his surgery, but that’s looking less likely now. “It’s not ideal,” manager Joe Espada said. “It sucks because I know he’s worked really hard. He wants to get on the field, he wants to pitch for us this season. I still expect him to do it. It’s just, we’re going to have to slow him down a little bit here and see how he feels. It’s day to day right now.”

It seems Espada still left the window open for Murfee to come back this year, but it’ll be tight just based on the calendar. Whenever he’s cleared to restart his rehab, he’ll presumably need a few outings to get into game shape after so much down time. The Astros have taken the lead in the West division and could perhaps increase the chances of Murfee playing a role if they manage to play deep into October yet again.

Even if that doesn’t come to pass, Murfee could play a role on the club in the future. He came into this season with one year and 169 days of service time. Players on the major league injured list collect service time, so he’ll finish this year at 2.169 as long as he’s not activated and then optioned in the next few weeks. He will qualify for arbitration as a Super Two player this winter but won’t be able to command a huge raise after so much missed time. The Astros can control him for four additional seasons beyond this one.

In another bit of Astros news, Chandler Rome of The Athletic relays on X that the club is going to give Alex Bregman some reps at first base. He recently missed a few games due to right elbow inflammation but has been in the last two contests as the designated hitter. Shay Whitcomb has been covering the hot corner of late while Bregman’s elbow is preventing him from making strong throws across the diamond, but perhaps he could handle first, where the throwing demands are lower.

While the club is surely glad to have Bregman’s bat back in the lineup, it currently makes for a slightly awkward fit as it forces Yordan Alvarez to play the field every day. The club has also given some DH time to Yainer Diaz this year, keeping his bat in the lineup whenever Victor Caratini is catching. If Bregman could slot in at first from time to time, it could give Espada a bit more flexibility in setting the lineup, getting Alvarez and Diaz a lighter workload as they approach the postseason.

First base has been a bit hole for the club this year, with José Abreu having been released after his immense struggles. Jon Singleton has largely taken over, with Zach Dezenzo also factoring in lately and Diaz moving there on occasion as well. Singleton is hitting .234/.314/.369 this year for a wRC+ of 97, almost league average but a bit below the expectations for a first baseman. Dezenzo has hit .188/.235/.313 in a small sample of 34 plate appearances. Bregman has hit .261/.319/.448 this year for a 117 wRC+ but has been even better lately. After cold start to the season, he has hit .296/.351/.512 since the start of June for a 145 wRC+.

' src=

I do not know why Astros thought all these injured pitchers could return this season. Pushing them to has caused 3 to be out rest of season

Murfee here, Garcia and McCullers. Whom I wonder will ever return. He should go to bullpen and be long man.

awe will not have Urquidy or France next season. If they even return. Talk was Urquidy May be non tendered this off season.

Javier will not pitch till perhaps late next season if he does not have set backs.

So for sure next season Framber, Brown. If they keep Blanco and Arrighetti. Not sure on Verlander.

' src=

I don’t know what’s going on behind the scenes with the Astros rehab/recovery program.

But I will say that every one of those pitchers are well beyond the usual minimum expected return time from their various injuries.

They may have messed something up in the rehab, but expecting them back too soon was not part of it.

' src=

Murfee’s Law.

' src=

So far the Penn is not mightier than the swo… scalpel.

' src=

is there anyone you haven’t muted? And we all appreciate you letting us know when you mute someone, thanks! (I really hope this gets you to mute me, if you haven’t already)

Leave a Reply Cancel reply

Please login to leave a reply.

Log in Register

list assignment in r

  • Feeds by Team
  • Commenting Policy
  • Privacy Policy

MLB Trade Rumors is not affiliated with Major League Baseball, MLB or MLB.com

FOX Sports Engage Network

Username or Email Address

Remember Me

free hit counter

  • SI SWIMSUIT
  • SI SPORTSBOOK

Angels Become Fourth Team to Designate Pitcher For Assignment in 2024

Maren angus-coombs | 13 hours ago.

list assignment in r

  • Los Angeles Angels

The Los Angeles Angels designated reliever Mike Baumann for assignment on Friday, per the  MLB transaction wire .

It was the fourth time this season that the 28-year-old right-hander was DFA'd.

Now that he's heading for waivers, other MLB teams will have a chance to claim him, but since he has more than two years of service time, he’ll need to be placed on a 40-man roster.

Baumann has never actually cleared waivers; in all three instances earlier this season, he was traded. He has gone from the Baltimore Orioles to the Seattle Mariners, San Francisco Giants and Angels via DFA resolutions throughout the year.

#Angels transactions: •Selected the contract of RHP Ryan Zeferjahn •Designated RHP Mike Baumann for assignment — Angels PR (@LAAngelsPR) August 23, 2024

When the Orioles designated him for assignment on May 18, they traded him four days later to the Seattle Mariners. Baltimore sent Baumann and catcher Michael Perez to the Mariners in exchange for catcher Blake Ford.

Seattle held onto him until July 19 and then traded him to the San Francisco Giants three days later. The Giants DFA’d him five days later and then traded him to the Angels, where he made 10 appearances.

Baumann has not pitched very well at any of his stops. He owns a 5.24 ERA through 44.2 innings this year.

Baumann had an outstanding season in 2023 when the Orioles clinched the American League East title. He posted a 10-1 record with a 3.76 ERA across 60 appearances, striking out 61 and walking 33 over 64.2 innings.

After three years at Jacksonville University, the Orioles selected Baumann in the third round of the 2017 draft.

He worked his way up to the big leagues and made his Major League Baseball debut with the Orioles in 2021, eventually becoming a reliable reliever.

During his time with Baltimore, he appeared in 94 games, posting a 13-5 record with a 4.45 ERA, 105 strikeouts, and 57 walks over 127.1 innings. Across his four MLB seasons, he holds a 15-5 record with a 4.80 ERA, 129 strikeouts, and 69 walks in 153.2 innings.

In a corresponding move, the Angels selected the contract of righty reliever Ryan Zeferjahn.

The Los Angeles Angels would have needed to add Zeferjahn to their 40-man roster this offseason to protect him from the Rule 5 draft. Instead, they’re giving him his first big league opportunity a few weeks early, allowing him to potentially secure a middle relief role heading into next season.

Maren Angus-Coombs

MAREN ANGUS-COOMBS

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

How do you use "<<-" (scoping assignment) in R?

I just finished reading about scoping in the R intro , and am very curious about the <<- assignment.

The manual showed one (very interesting) example for <<- , which I feel I understood. What I am still missing is the context of when this can be useful.

So what I would love to read from you are examples (or links to examples) on when the use of <<- can be interesting/useful. What might be the dangers of using it (it looks easy to loose track of), and any tips you might feel like sharing.

  • lexical-scope

Bhargav Rao's user avatar

  • 1 I've used <<- to preserve key variables generated inside a function to record in failure logs when the function fails. Can help to make the failure reproducible if the function used inputs (e.g. from external APIs) that wouldn't necessarily have been preserved otherwise due to the failure. –  geotheory Commented Oct 9, 2020 at 11:59

7 Answers 7

<<- is most useful in conjunction with closures to maintain state. Here's a section from a recent paper of mine:

A closure is a function written by another function. Closures are so-called because they enclose the environment of the parent function, and can access all variables and parameters in that function. This is useful because it allows us to have two levels of parameters. One level of parameters (the parent) controls how the function works. The other level (the child) does the work. The following example shows how can use this idea to generate a family of power functions. The parent function ( power ) creates child functions ( square and cube ) that actually do the hard work.

The ability to manage variables at two levels also makes it possible to maintain the state across function invocations by allowing a function to modify variables in the environment of its parent. The key to managing variables at different levels is the double arrow assignment operator <<- . Unlike the usual single arrow assignment ( <- ) that always works on the current level, the double arrow operator can modify variables in parent levels.

This makes it possible to maintain a counter that records how many times a function has been called, as the following example shows. Each time new_counter is run, it creates an environment, initialises the counter i in this environment, and then creates a new function.

The new function is a closure, and its environment is the enclosing environment. When the closures counter_one and counter_two are run, each one modifies the counter in its enclosing environment and then returns the current count.

abbassix's user avatar

  • 6 Hey this is an unsolved R task on Rosettacode ( rosettacode.org/wiki/Accumulator_factory#R ) Well, it was... –  Karsten W. Commented Apr 15, 2010 at 15:05
  • 1 Would there be any need to enclose more than 1 closures in one parent function? I just tried one snippet, it seems that only the last closure was executed... –  Oliver Commented Feb 3, 2018 at 15:13
  • Is there any equal sign alternative to the "<<-" sign? –  Saren Tasciyan Commented May 1, 2019 at 15:46

It helps to think of <<- as equivalent to assign (if you set the inherits parameter in that function to TRUE ). The benefit of assign is that it allows you to specify more parameters (e.g. the environment), so I prefer to use assign over <<- in most cases.

Using <<- and assign(x, value, inherits=TRUE) means that "enclosing environments of the supplied environment are searched until the variable 'x' is encountered." In other words, it will keep going through the environments in order until it finds a variable with that name, and it will assign it to that. This can be within the scope of a function, or in the global environment.

In order to understand what these functions do, you need to also understand R environments (e.g. using search ).

I regularly use these functions when I'm running a large simulation and I want to save intermediate results. This allows you to create the object outside the scope of the given function or apply loop. That's very helpful, especially if you have any concern about a large loop ending unexpectedly (e.g. a database disconnection), in which case you could lose everything in the process. This would be equivalent to writing your results out to a database or file during a long running process, except that it's storing the results within the R environment instead.

My primary warning with this: be careful because you're now working with global variables, especially when using <<- . That means that you can end up with situations where a function is using an object value from the environment, when you expected it to be using one that was supplied as a parameter. This is one of the main things that functional programming tries to avoid (see side effects ). I avoid this problem by assigning my values to a unique variable names (using paste with a set or unique parameters) that are never used within the function, but just used for caching and in case I need to recover later on (or do some meta-analysis on the intermediate results).

Shane's user avatar

  • 4 Thanks Tal. I have a blog, although I don't really use it. I can never finish a post because I don't want to publish anything unless it's perfect, and I just don't have time for that... –  Shane Commented Apr 13, 2010 at 13:44
  • 5 A wise man once said to me it is not important to be perfect - only out standing - which you are, and so will your posts be. Also - sometimes readers help improve the text with the comments (that's what happens with my blog). I hope one day you will reconsider :) –  Tal Galili Commented Apr 13, 2010 at 15:25

One place where I used <<- was in simple GUIs using tcl/tk. Some of the initial examples have it -- as you need to make a distinction between local and global variables for statefullness. See for example

which uses <<- . Otherwise I concur with Marek :) -- a Google search can help.

Dirk is no longer here's user avatar

  • Interesting, I somehow cannot find tkdensity in R 3.6.0. –  NelsonGon Commented Jun 26, 2019 at 16:22
  • 1 The tcltk package ships with R: github.com/wch/r-source/blob/trunk/src/library/tcltk/demo/… –  Dirk is no longer here Commented Jun 26, 2019 at 16:30

On this subject I'd like to point out that the <<- operator will behave strangely when applied (incorrectly) within a for loop (there may be other cases too). Given the following code:

you might expect that the function would return the expected sum, 6, but instead it returns 0, with a global variable mySum being created and assigned the value 3. I can't fully explain what is going on here but certainly the body of a for loop is not a new scope 'level'. Instead, it seems that R looks outside of the fortest function, can't find a mySum variable to assign to, so creates one and assigns the value 1, the first time through the loop. On subsequent iterations, the RHS in the assignment must be referring to the (unchanged) inner mySum variable whereas the LHS refers to the global variable. Therefore each iteration overwrites the value of the global variable to that iteration's value of i , hence it has the value 3 on exit from the function.

Hope this helps someone - this stumped me for a couple of hours today! (BTW, just replace <<- with <- and the function works as expected).

OTStats's user avatar

  • 4 in your example, the local mySum is never incremented but only the global mySum . Hence at each iteration of the for loop, the global mySum get the value 0 + i . You can follow this with debug(fortest) . –  ClementWalter Commented Oct 26, 2015 at 16:49
  • It's got nothing to do with it being a for-loop; you're referencing two different scopes. Just use <- everywhere consistently within the function if you only want to update the local variable inside the function. –  smci Commented Apr 29, 2016 at 3:08
  • Or use <<-- everywhere @smci. Though best to avoid globals. –  Union find Commented Dec 5, 2017 at 4:15
  • As far as I understand, R is NOT scoped withing braces { }, which is different from many other languages. The scoping is within functions. So, <<- does not access the mySum outside of the for loop as you might expect; rather, it accesses mySum outside of the fortest function. In the first run, mySum did not exist outside of fortest , so it was created, initialized as zero, and then incremented. Each subsequent iteration of the for loop iterates the global mySum again. So, the mySum in fortest always stays as zero but a global mySum is created and incremented to 3. –  Tripartio Commented Jan 3 at 13:14

lcgong's user avatar

  • 12 This is a good example of where not to use <<- . A for loop would be clearer in this case. –  hadley Commented Apr 13, 2010 at 14:15

The <<- operator can also be useful for Reference Classes when writing Reference Methods . For example:

Carlos Cinelli's user avatar

I use it in order to change inside purrr::map() an object in the global environment.

Say I want to obtain a vector which is c(1,2,3,1,2,3,4,5), that is if there is a 1, let it 1, otherwise add 1 until the next 1.

Tripartio's user avatar

  • This tiny answer explains what brought me to this question--why <- often does not work in purrr::map and I have to use <<- . Now I get it: purrr::map does its work inside a function and there only function scope applies. So, super-assignment <<- is required to modify variables outside of the purrr::map internal function (the .f argument). –  Tripartio Commented Jan 3 at 13:18

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged r scoping lexical-scope r-faq or ask your own question .

  • The Overflow Blog
  • LLMs evolve quickly. Their underlying architecture, not so much.
  • From PHP to JavaScript to Kubernetes: how one backend engineer evolved over time
  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Bringing clarity to status tag usage on meta sites
  • What does a new user need in a homepage experience on Stack Overflow?
  • Feedback requested: How do you use tag hover descriptions for curating and do...
  • Staging Ground Reviewer Motivation

Hot Network Questions

  • Why do I get two values for the following limit using two different methods with the same identity?
  • How to ensure a BSD licensed open source project is not closed in the future?
  • How do I make my table span the entire textwidth without affecting the height
  • Does a MySQL replication slave need to be as powerful as the master?
  • Meaning of 拵えた here
  • "can-do" vs. "can-explain" fallacy
  • Seifert surfaces of fibered knots
  • Canceling factors in a ratio of factorials
  • degeneration of a Veronese surface
  • Can You Replace an Aberrant Mind Sorcerer Spell with a Spell and Learn the Replaced Spell as a Standard Sorcerer Spell During the Same Level-Up
  • What was I thinking when I made this grid?
  • Can light become a satellite of a black hole?
  • In theory, could an object like 'Oumuamua have been captured by a three-body interaction with the sun and planets?
  • Completely introduce your friends
  • Why cant we save the heat rejected in a heat engine?
  • Crystal Oscillator Waveform
  • Repeating zsh brace expansion values in zsh to download multiple files using wget2
  • using a tikz foreach loop inside a newcommand
  • Top tube structural question
  • What is the name of the book about a boy dressed in layers of clothes that isn't a boy?
  • Why did General Leslie Groves evade Robert Oppenheimer's question here?
  • Quality difference between Sigma 30mm f1.4 Art and Contemporary
  • Can I retain the ordinal nature of a predictor while answering a question about it that is inherently binary?
  • Electric skateboard: helmet replacement

list assignment in r

COMMENTS

  1. R Lists (With Examples)

    The structure of the above list can be examined with the str() function. str(x) Output. List of 3. $ a:num 2.5. $ b:logi TRUE. $ c:int [1:3] 1 2 3. In this example, a, b and c are called tags which makes it easier to reference the components of the list. However, tags are optional.

  2. R: using assign() for list elements

    Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers; Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand; OverflowAI GenAI features for Teams; OverflowAPI Train & fine-tune LLMs; Labs The future of collective knowledge sharing; About the company Visit the blog

  3. How to Create a List in R (With Examples)

    Here are the two most common ways to create a list in R: Method 1: Create a List. #create list. my_list <- list(c('A', 'B', 'C'), 14, 20, 23, 31, 'Thunder', 'Wizards') This particular example creates a list named my_list that contains a variety of elements with different data types. Method 2: Create a Named List. #create named list.

  4. 6 Lists and data frames

    6.3 Data frames. A data frame is a list with class "data.frame". There are restrictions on lists that may be made into data frames, namely. The components must be vectors (numeric, character, or logical), factors, numeric matrices, lists, or other data frames. Matrices, lists, and data frames provide as many variables to the new data frame as ...

  5. R List: Create a List in R with list()

    Learn about and create R lists. Practice creating lists with exercises and code examples using the function list(). Practice the course material from DataCamp's Intro to R course today!

  6. LIST in R language ⚡ [CREATE, COMPARE, JOIN, EXTRACT, ... ]

    What is a list in R? A list in R programming language is an ordered collection of any R objects.Thus, although the elements of vectors, matrix and arrays must be of the same type, in the case of the R list the elements can be of different type.Therefore, you can mix several data types with this structure.. Create a list in R

  7. Chapter 9 Lists

    Chapter 9. Lists. In terms of 'data types' (objects containing data) we have only been working with atomic vectors and matrices which are both homogenous objects - they can always only contain data of one specific type. Figure 9.1: As we will learn, data frames are typically lists of atomic vectors of the same length.

  8. R List

    What is a List? Vectors and matrices are incredibly useful data structure in R, but they have one distinct limitation: they can store only one type of data. Lists, however, can store multiple types of values at once. A list can contain a numeric matrix, a logical vector, a character string, a factor object and even another list. Create a List

  9. Assignment Operators in R (3 Examples)

    On this page you'll learn how to apply the different assignment operators in the R programming language. The content of the article is structured as follows: 1) Example 1: Why You Should Use <- Instead of = in R. 2) Example 2: When <- is Really Different Compared to =. 3) Example 3: The Difference Between <- and <<-.

  10. Introduction to Lists in R. Lists can hold components of different

    For you to try (2) Create a list for the movie "The Shining", which contains three components: moviename — a character string with the movie title (stored in mov); actors — a vector with the names of the main actors (stored in act); reviews — a data frame that contains some reviews (stored in rev) # Character variable for movie name mov <- "The Shining" # Vector for the names of the ...

  11. R

    R - Lists. A list in R programming is a generic object consisting of an ordered collection of objects. Lists are one-dimensional, heterogeneous data structures. The list can be a list of vectors, a list of matrices, a list of characters, a list of functions, and so on. A list is a vector but with heterogeneous data elements.

  12. Twins' Byron Buxton 'getting closer,' might get rehab assignment

    Center fielder Byron Buxton is "getting closer" and likely to get a rehab assignment when he's ready to return to the Twins lineup, manager Rocco Baldelli said ahead of Monday's game against ...

  13. R List (with Examples)

    Access List Elements in R. In R, each element in a list is associated with a number. The number is known as a list index. We can access elements of a list using the index number (1, 2, 3 …).For example,

  14. list function

    For functions, this returns the concatenation of the list of formal arguments and the function body. For expressions, the list of constituent elements is returned. as.list is generic, and as the default method calls as.vector (mode = "list") for a non-list, methods for as.vector may be invoked. as.list turns a factor into a list of one-element ...

  15. How to Create a List of Lists in R (With Example)

    Example: Create List of Lists in R. The following code shows how to create a list that contains 3 lists in R: #define lists list1 <- list(a=5, b=3) list2 <- list(c='A', d=c('B', 'C')) list3 <- list(e=c(20, 5, 8, 16)) ...

  16. R Lists

    W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

  17. R: Assign Values In a List to Names

    Assign Values In a List to Names Description. Assigns the values in a list to variables in an environment. The variable names are taken from the names of the list, so all of the elements of the list must have non-blank names. Usage assignList(aList, pos = -1, envir = as.environment(pos), inherits = FALSE) Arguments

  18. R: Assign nested components of a list to names

    Assign nested components of a list to names Description. The %<<-% operator assigns multiple (nested) components of a list or vector to names via pattern matching ("unpacking assignment"). Think of the "dub(ble) arrow" <<-as a pictograph representing multiple <-'s. %<<-% is especially convenient for: assigning individual names to the multiple values that a function may return in the ...

  19. Using R, Randomly Assigning Students Into Groups Of 4

    Instead of having R select rows and put them into a new data frame, I decided to have R assign a random number to each of the students and then sort the data frame by the number: First, I broke up the data frame into sections: Then I randomly generated a group number 1 through 4. Next, I told R to bind the columns:

  20. Astros Shut Down Penn Murfee's Rehab Assignment

    Right-hander Penn Murfee began a rehab assignment last week but made just one appearance and will now be shut down. ... Players on the major league injured list collect service time, so he'll ...

  21. r

    @ClarkThomborson The semantics are fundamentally different because in R assignment is a regular operation which is performed via a function call to an assignment function. However, this is not the case for = in an argument list. In an argument list, = is an arbitrary separator token which is no longer present after parsing. After parsing f(x = 1), R sees (essentially) call("f", 1).

  22. Angels Become Fourth Team to Designate Pitcher For Assignment in 2024

    The Los Angeles Angels designated reliever Mike Baumann for assignment on Friday, per the MLB transaction wire. It was the fourth time this season that the 28-year-old right-hander was DFA'd.

  23. r

    I have a dataframe that I would like to convert to a nested list, by row. However, I need to group several columns into separate matrices in each nested element. All of the solutions I've seen put each column into a unique element. I want to create separate matrices using the column values. For example, if I have a dataframe as below:

  24. How do you use "<<-" (scoping assignment) in R?

    Using <<- and assign(x, value, inherits=TRUE) means that "enclosing environments of the supplied environment are searched until the variable 'x' is encountered." In other words, it will keep going through the environments in order until it finds a variable with that name, and it will assign it to that.