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.

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.

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.

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

  • 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

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

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.

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

How to Apply the ifelse Function without an else Output in R (4 Examples)

How to Apply the ifelse Function without an else Output in R (4 Examples)

Calculate Difference Between Consecutive Rows in R (Example)

Calculate Difference Between Consecutive Rows in R (Example)

Independence Day of India, 15 August 2024: History, Significance, Facts and all you need to know

Independence Day of India, 15 August 2024: History, Significance, Facts and all you need to know

The history of Indian independence

Independence (1)

I told you he was over but I didn’t think they’d figure it out this fast. Did he even pitch?

' src=

Once. 3 batters faced. 2 walks, 1 hit

Sounds about right.

' src=

I thought you guys were talking about Darvish pitching against high school boys, and I thought, “Whoa, those three boys must feel great right now, and the rest of the team must be disappointed that he just stopped after three hitters.”

' src=

Yep 7,8,9 hitters and didn’t get an out.

' src=

I expected him to be the DFA (and agree) option but really, I’m giving him a pass on that last outing due to his schedule. The guy was with the AAA team the night before, drove 2 hours to an airport in Texas at like 7 am to fly and arrive at the ballpark, I think around the 2nd inning.

Tough circumstances to at least not overlook when talking about his stat line is all I’m saying.

' src=

He had a rough go in 19 with the Padres as well. I’ve seen him be good other places. I hope he lands on his feet.

' src=

Darvish out since end of May. This August. Five weeks? Don’t tell me he’s gambling too…..

' src=

No no…the other Japanese player who DHs

' src=

Sorry CARL, Back to NASCAR !!

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

Streamflation: Disney+ and Hulu price hikes and how much it really costs to stream TV

list assignment in r

Streaming is getting way more expensive.

Somehow over the past few years, streaming services, once considered a cost-effective way to watch TV, have become so expensive that getting a handful to watch your favorite shows can rival your cable bill. And all these price hikes might have escaped notice by inching up a dollar or two at a time. Disney+ and Hulu prices will jump in October. Paramount+ goes up on Aug. 20. Peacock also raised its prices in August.

It might surprise you, but here are the current and upcoming prices and plans available for the eight major entertainment TV streamers (excluding bundles), plus Venu , the all-new sports-only service from Disney, Warner Bros. Discovery and Fox.

How much does Netflix cost?

◾ With ads: $6.99/month.

◾ No Ads, two supported devices: $15.49/month ( extra member slots can be added for $7.99 each).

◾ No ads, four supported devices, 4K: $22.99/month ( extra member slots can be added for $7.99 each).

What you get: The original streamer often has the buzziest shows and movies, including "Baby Reindeer" and "Beverly Hills Cop: Axel F," and a large library of content. There are also games, WWE Raw coming in 2025, some live events like comedy specials and the SAG Awards. The streamer is also dipping its toe into the waters of live sports and will have two NFL games on Christmas Day: the Kansas City Chiefs at Pittsburgh Steelers and the Baltimore Ravens at Houston Texans.

How much does Disney+ cost?

◾ With Ads: $9.99/month.

◾ No Ads: $15.99 or $159.99/year.

What you get: It's not just kids stuff, Marvel and "Star Wars" anymore, but that's a lot of it! The family-friendly streamer also has popular originals like "Percy Jackson and the Olympians," live events like an Elton John concert and the Rock Hall induction ceremony and National Geographic programming. Prices effective on Oct. 17.

How much does Hulu cost?

◾ With Ads: $9.99/month or $99.99/year.

◾ No Ads: $18.99/month.

What you get: Hulu originals like "The Bear" and "Only Murders in the Building," plus some theatrical and streaming-only movies and next-day episodes from most ABC, Fox and FX series. Prices effective in October.

How much does Amazon Prime Video cost?

◾ Prime Video only with ads: $8.99/month.

◾ With ads and full Prime benefits, including free shipping: $14.99/month or $139/year.

◾ Ad-free and full Prime benefits: $17.98/month, or $139/year plus $2.99/month.

What you get: Amazon has the full gamut of shows from big-budget "Lord of the Rings: The Rings of Power" to your dad's favorites like "Reacher" and "Jack Ryan" and a wide variety of new and old movies and TV series. The service also has exclusive rights to the NFL's "Thursday Night Football."

How much does Max cost?

◾ With ads: $9.99/month or $99.99/year.

◾ Without ads: $16.99/month or $169.99/year.

◾ "Ultimate" without ads (4K, four supported devices): $20.99/month or $209.99/year.

What you get : All HBO content ; originals including "The Sex Lives of College Girls"; Discovery programming from HGTV, TLC and Food Network; Turner Classic Movies; CNN content; and Warner Bros. movies such as "Barbie." Parent company Warner Bros. Discovery has recently shifted its highest-profile Max originals to HBO, including the upcoming Batman villain series "The Penguin," but they will still be available on Max. Some sports are available with an add-on subscription to Bleacher Report.

How much does Peacock cost?

◾ Premium (with ads): $7.99/month or $79.99/year.

◾ Premium Plus (without ads): $13.99/month or $139.99/year.

What you get: "The Office" is only on Peacock, along with next-day streams of NBC and Bravo content like "Saturday Night Live" and originals including "The Traitors" and "Poker Face." It is also the only streaming home for the Olympics , as well as other NBC sports such as "Sunday Night Football." You can also stream your local NBC affiliate, live.

How much does Paramount+ cost?

◾ Paramount+ Essential (with ads): $7.99/month or $59.99/year.

◾ Paramount+ with SHOWTIME (no ads): $12.99/month or $119.99/year.

What you get: CBS shows old and new, some classic movies and TV and originals like the "Frasier" reboot and the many "Yellowstone" spinoffs. You can stream CBS live, which includes any sports that air on CBS like NFL games, soccer and golf. You can also catch up on your CBS shows the next day. If you spring for the ad-free plan with Showtime, you also get that premium channel's content, including Emmy-nominated "Yellowjackets" and the "Dexter" revival.

How much does Apple TV+ cost?

◾ Without ads: $9.99/month.

What you get: Apple original series and movies, such as "Ted Lasso" and "Killers of the Flower Moon." Apple also has been making big plays in the sports world, with exclusive rights to "Friday Night Baseball" and Major League Soccer games. What Apple notably doesn't have is a large library of old shows and movies: It only has originals it's been making since the service was introduced in 2019.

How much does Venu cost?

◾ With ads: $42.99/month.

What you get: The new sports-only streamer provides a way to watch a lot (but not all) live sports for consumers who have cut the cable cord. The venture comes from Warner Bros. Discovery, Disney, and Fox is due in time for the college football season and includes professional baseball, basketball, football, hockey and soccer leagues. College sports include NCAA football, NCAA men's and women's basketball, motorsports including NASCAR and Formula 1 events, Grand Slam tennis, golf, boxing and MMA. However, because Comcast and Paramount are not involved, sports that air on NBC or CBS, such as the Olympics and NFL games including "Sunday Night Football," aren't included. But on Aug. 16, a judge granted Internet TV provider Fubo an injunction halting Venu's launch on antitrust grounds, forcing the service to scrap a planned Aug. 23 launch date.

You can easily compare the prices in the chart below.

So just how expensive is all that? Choosing monthly subscriptions to separate ad-supported plans for all eight streamers would run you $77.92, once announced price hikes take effect, excluding Venu. To get them ad-free, you'd pay $122.41. Add in Venu and that's $120.91 for the with-commercials plans and $165.40 for the ad-free plans.

So is the cost worth it? That depends on your individual tastes and priorities. Few consumers will opt for all eight major services, but if you want to watch every show nominated for the best drama and best comedy categories at this year's Emmy Awards , you'd need to subscribe to five of them.

It's a reminder to keep an eye on your credit card statements and be choosy about what services you really watch. Maybe you got Peacock for the Olympics but you've never watched a single show or movie. You could probably have canceled after the closing ceremony.

And with all these price increases and bundles, the old world of cable doesn't look so bad anymore.

Boston Red Sox | Red Sox designate veteran infielder for…

Share this:.

  • Click to share on Facebook (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to print (Opens in new window)

Boston Red Sox

  • New England Patriots
  • Boston Celtics
  • Boston Bruins
  • High School

Boston Red Sox | Red Sox designate veteran infielder for assignment amidst Triston Casas’ return

Boston Red Sox first baseman Dominic Smith tips his cap after pitching during the ninth inning of a baseball game against the Houston Astros, Sunday, Aug. 11, 2024, in Boston. (AP Photo/Michael Dwyer)

FanSided’s MLB insider Robert Murray reported Friday afternoon that the club is designating first baseman Dom Smith for assignment.

The news comes hours after the Herald confirmed that Triston Casas had left his rehab assignment in Triple-A Worcester and was on his way to Baltimore to rejoin the big-league team.

After spending the first six years of his big-league career with the New York Mets and last season with the Washington Nationals, Smith, 29, signed with the Red Sox at the beginning of May. He signed with the club knowing that his time in Boston was likely contingent on Casas’ absence, but was a valuable contributor during his 83 games; he hit .237 with a .706 OPS, 25 walks, and 65 strikeouts. He homered six times and collected 20 doubles, tied for the second-most of his career. He ranked in the 80th MLB percentile in Launch-Angle Sweet-Spot rate,

Smith also achieved a rare feat in MLB’s Universal Designated Hitter Era: he’s the only player to hit a home run and pitch for the Red Sox this season. He made his pitching debut this season, closing out three of Boston’s blowout losses. Over three innings, he gave up two hits and issued one walk, but allowed no runs.

The Red Sox also optioned right-hander Chase Shugart to Triple-A in order to reinstate right-hander Cooper Criswell from the 7-day COVID-related injured list.

More in Boston Red Sox

Earlier this week the Red Sox top three prospects were all called up to Triple-A. When can fans realistically expect to see them in the majors?

SUBSCRIBER ONLY

Boston red sox | mlb notes: when can fans realistically expect red sox ‘big three’ to reach the majors.

How Red Sox legends unknowingly prepared top prospect Marcelo Mayer for the spotlight

Boston Red Sox | How Red Sox legends unknowingly prepared top prospect Marcelo Mayer for the spotlight

Red Sox hand Orioles ace Corbin Burnes the worst start of his career in 12-10 win

Boston Red Sox | Red Sox hand Orioles ace Corbin Burnes the worst start of his career in 12-10 win

Red Sox lineup: Casas back from IL, Bernardino opening bullpen game

Boston Red Sox | Red Sox lineup: Casas back from IL, Bernardino opening bullpen game

  • SI SWIMSUIT
  • SI SPORTSBOOK

Former Cleveland Guardians Star Likely To Be Replaced As White Sox Manager

Matthew schmidt | aug 16, 2024.

Aug 9, 2024; Chicago, Illinois, USA; Chicago White Sox interim manager Grady Sizemore (24) looks on from the dugout before a baseball game against the Chicago Cubs at Guaranteed Rate Field. Mandatory Credit: Kamil Krzaczynski-USA TODAY Sports

  • Cleveland Guardians
  • Chicago White Sox

The Chicago White Sox fired manager Pedro Grifol earlier this month and named former Cleveland Guardians star Grady Sizemore the team's interim manager.

However, it doesn't seem like Sizemore will have a very long stay as White Sox skipper.

Chicago intends to go outside of the organization to land its next manager, via Jon Heyman of The New York Post . This comes in spite of the fact that Sizemore is beloved by the players.

Of course, Guardians fans know Sizemore for his electrifying—but injury-riddled—nine-year tenure with Cleveland from 2004 through 2012.

The former outfielder made three straight All-Star appearances from 2006 through 2008, with his best season coming in 2006 when he slashed .290/.375/.533 with 28 home runs and 76 RBI over 751 plate appearances. He also tallied a league-leading 53 doubles and stole 22 bases.

A true five-tool talent, Sizemore was one of the very best players in baseball for a brief stretch, adding a couple of Gold Gloves and a Silver Slugger award to his resume.

Unfortunately, it didn't take long for injuries to take their toll on the Seattle native.

After missing just nine games in total between 2005 and 2008, Sizemore would then play in 106, 33 and 71 games the next three seasons, respectively.

He would proceed to miss all of 2012 and 2013, and in the latter campaign, Sizemore was not even on an MLB roster.

The 42-year-old made his return in 2014 and played two more seasons, spending time with the Boston Red Sox, Philadelphia Phillies and Tampa Bay Rays. However, he was never able to regain his previous form.

Throughout his time in Cleveland, Sizemore slashed .269/.357/.473 with 139 homers.

Matthew Schmidt

MATTHEW SCHMIDT

  • 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
  • Navigating cities of code with Norris Numbers
  • 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
  • Feedback requested: How do you use tag hover descriptions for curating and do...

Hot Network Questions

  • Has technology regressed in the Alien universe?
  • What is the meaning of these Greek words ἵπποπείρην and ἐπεμβάτην?
  • Giant War-Marbles of Doom: What's the Biggest possible Spherical Vehicle we could Build?
  • How predictable are the voting records of members of the US legislative branch?
  • Did the United States have consent from Texas to cede a piece of land that was part of Texas?
  • The complement of a properly embedded annulus in a handlebody is a handlebody
  • Where exactly was this picture taken?
  • Why HIMEM was implemented as a DOS driver and not a TSR
  • Power line crossing data lines via the ground plane
  • Age is just a number!
  • How do you "stealth" a relativistic superweapon?
  • Advice needed: Team needs developers, but company isn't posting jobs
  • 90/180 day rule with student resident permit, how strict it is applied
  • Why do these finite group Dedekind matrices seem to have integer spectrum when specialized to the order of group elements?
  • What is a transition of point man in French?
  • Dial “M” for murder
  • Garage door not closing when sunlight is bright
  • How to cite a book if only its chapters have DOIs?
  • They come in twos
  • when translating a video game's controls into German do I assume a German keyboard?
  • Polar coordinate plot incorrectly plotting with PGF Plots
  • Does a Way of the Astral Self Monk HAVE to do force damage with Arms of the Astral Self from 10' away, or can it be bludgeoning?
  • conflict of \counterwithin and cleveref package when sectioncounter is reset
  • Venus’ LIP period starts today, can we save the Venusians?

list assignment in r

IMAGES

  1. R List

    list assignment in r

  2. Lists in R Programming: Purpose & Examples

    list assignment in r

  3. Introduction to Lists in R

    list assignment in r

  4. R List

    list assignment in r

  5. Lists in R

    list assignment in r

  6. How to Create a List in R?

    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. Assigning value to the list element in R

    That's not what you are trying to do. You want subassignment into the list. However, assuming you have some arbitrary named list, hopefully you know at least the environment containing that list. Then you can do this: .GlobalEnv[[paste0("x_",1)]][[1]] <- 6. answered Aug 28, 2016 at 13:11. Roland.

  3. 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 ...

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

    Creating a list. Let us create our first list! To construct a list you use the function list(): my_list <- list( comp1, comp2 ...) The arguments to the list function are the list components. Remember, these components can be matrices, vectors, other lists, ...

  5. 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.

  6. How to Append Values to List in R (With Examples)

    How to Append Values to List in R (With Examples) You can use the following syntax to append a single value to a list in R: len <- length(my_list) And you can use the following syntax to append multiple values to a list in R: len <- length(my_list) #define values to append to list. new <- c(3, 5, 12, 14)

  7. 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

  8. 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.

  9. 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 ...

  10. 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 ...

  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. 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

  13. 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.

  14. 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 <<-.

  15. How to Use the assign() Function in R (3 Examples)

    The assign() function in R can be used to assign values to variables. This function uses the following basic syntax: assign(x, value) where: x: A variable name, given as a character string. value: The value(s) to be assigned to x. The following examples show how to use this function in practice. Example 1: Assign One Value to One Variable

  16. 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 ...

  17. Phillies Make Six Roster Moves

    To open 40-man spots for those two, first baseman Darick Hall and righty Max Castillo have been designated for assignment. Hays left Wednesday's game with left hamstring tightness, per Todd ...

  18. Braves Designate Parker Dunshee For Assignment

    Outfielder Eli White was optioned to Triple-A to open an active roster spot while right-hander Parker Dunshee was designated for assignment in a corresponding 40-man move.

  19. DNC speaker schedule: See which big names will speak in Chicago

    NBC News reported that President Jimmy Carter's grandson Jason Carter will speak on behalf of his grandfather. The DNC speaker schedule is subject to change and a full list of speakers will be ...

  20. Why doesn't assign() values to a list element work in R?

    From the help file: 'assign' 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 'attach' and 'with'. If you're passing names(x) as input, couldn't you use: x[[n ...

  21. Here are the Winners of the 2024 Edward R. Murrow Awards

    The 2024 Edward R. Murrow Awards winners were announced on Thursday, with ABC News, CBS News and Al Jazeera's digital arm emerging as big winners. Named after the esteemed radio and television ...

  22. Independence Day of India, 15 August 2024: History, Significance, Facts

    On August 15, 1947, India gained independence after 90 years of British rule. This day marks the culmination of a prolonged struggle led by freedom fi

  23. Will Padres' Yu Darvish Be Back in 2024? Report Puts Chances at No

    His hiatus from baseball came shortly after Darvish was sent on rehab assignment to the Fort Wayne TinCaps for a left groin strain in the beginning of June. The 2020 All-MLB First-Team selection ...

  24. 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)) ...

  25. Padres Reinstate Joe Musgrove, Designate Carl Edwards

    As expected, the Padres reinstated Joe Musgrove from the 60-day injured list to start tonight's game against the Pirates. San Diego designated reliever Carl Edwards Jr. for assignment to open ...

  26. List of all streaming services and prices (yes, costs are rising)

    How much does Disney+ cost? With Ads: $9.99/month. No Ads: $15.99 or $159.99/year. What you get: It's not just kids stuff, Marvel and "Star Wars" anymore, but that's a lot of it! The family ...

  27. Red Sox designate veteran infielder for assignment amidst young star's

    With Triston Casas coming off the injured list to face the Orioles, the Red Sox designated veteran first baseman Dom Smith for assignment after 83 games.

  28. 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).

  29. Former Cleveland Guardians Star Likely To Be Replaced As White Sox Manager

    The Chicago White Sox fired manager Pedro Grifol earlier this month and named former Cleveland Guardians star Grady Sizemore the team's interim manager. However

  30. 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.